Section 7.13. Obtaining the Time Zone


7.12. Detecting Leap Years

The Date class has two class methods julian_leap? and gregorian_leap?; only the latter is of use in recent years. It also has a method leap?, which is an alias for the gregorian_leap? method.

require "date" flag1 = Date.julian_leap? 1700     # true flag2 = Date.gregorian_leap? 1700  # false flag3 = Date.leap? 1700            # false


Every child knows the first rule for leap years: The year number must be divisible by four. Fewer people know the second rule, that the year number must not be divisible by 100; and fewer still know the exception, that the year can be divisible by 400. In other words: A century year is a leap year only if it is divisible by 400, so 1900 was not a leap year, but 2000 was. (This adjustment is necessary because a year is not exactly 365.25 days, but a little less, approximately 365.2422 days.)

The Time class does not have a method like this, but if we needed one, it would be simple to create.

class Time   def Time.leap? year     if year % 400 == 0       true     elsif year % 100 == 0       false     elsif year % 4 == 0       true     else       false   end end


I've written this to make the algorithm explicit; an easier implementation, of course, would be simply to call the Date.leap? method from this one. I implement this as a class method by analogy with the Date class methods. It could also be implemented as an instance method.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net