Easy way to determine leap year in ruby?
For your understanding:
def leap_year?(year)
if year % 4 == 0
if year % 100 == 0
if yearVar % 400 == 0
return true
end
return false
end
return true
end
false
end
This could be written as:
def leap_year?(year)
(year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0)
end
Use Date#leap?
.
now = DateTime.now
flag = Date.leap?( now.year )
e.g.
Date.leap?( 2018 ) # => false
Date.leap?( 2016 ) # => true
Try this:
is_leap_year = year % 4 == 0 && year % 100 != 0 || year % 400 == 0
Here is my answer for the exercism.io problem which asks the same question. You are explicitly told to ignore any standard library functions that may implement it as part of the exercise.
class Year
attr_reader :year
def initialize(year)
@year = year
end
def leap?
if @year.modulo(4).zero?
return true unless @year.modulo(100).zero? and not @year.modulo(400).zero?
end
false
end
end