Easy way to determine leap year in ruby?

2019-03-23 08:34发布

Is there an easy way to determine if a year is a leap year?

9条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-23 09:15

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
查看更多
爷的心禁止访问
3楼-- · 2019-03-23 09:20

Any year that is evenly divisible by 4 is a leap year. However, there is still a small error that must be accounted for. To eliminate this error, the Gregorian calendar stipulates that a year that is evenly divisible by 100 (for example, 1900) is a leap year only if it is also evenly divisible by 400.

class Date

  def self.leap?(year)
    year % 4 == 0 && year % 100 != 0 || year % 400 == 0
  end

end
查看更多
闹够了就滚
4楼-- · 2019-03-23 09:21

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
查看更多
登录 后发表回答