Calculating the next leap year in Ruby
I needed to calculate the next leap year today, and was happy to find out about Date.leap?
via this StackOverflow question.
However, there wasn’t a built-in way that I could find to get the next leap year. It turned out to be pretty simple, but still worth sharing.
# next_leap_year.rb
# License: MIT
require "date"
def next_leap_year(year)
year += 1 until Date.leap?(year)
year
end
require "minitest/spec"
require "minitest/autorun"
describe "next_leap_year" do
describe "given a leap year" do
it "returns the same year" do
assert_equal(next_leap_year(2012), 2012)
end
end
describe "given a non-leap year" do
it "returns the next leap year" do
assert_equal(next_leap_year(2013), 2016)
end
end
end