Morton Goldberg
11/7/2006 8:09:00 PM
On Nov 7, 2006, at 12:15 PM, Shiloh Madsen wrote:
> So, I'm trying to go through the Teach Yourself Programming book by
> Pragmatic Press and I am encountering a few hurdles. The chapter I am
> working on now is asking me to create a program which will ask for a
> start and end year and then calculate all leap years in that range.
> The logic behind leap years (for those who need a refresher) is all
> years divisible by for are leap years EXCEPT those that are divisible
> by 100 UNLESS they are also divisible by 400. I am somewhat at a loss
> for how to handle the logic for this...finding all numbers that are
> divisible by 4 and removing those divisible by 100 is easy. Its adding
> in that third condition which adds some of the removed numbers back
> into the "true" group that I am having trouble with...or maybe I am
> just not wrapping my mind around the problem well
> enough...suggestions?
Here is simple way:
1. Write a is_leap? method.
def is_leap?(y)
return true if y % 400 == 0
return false if y % 100 == 0
return true if y % 4 == 0
false
end
2. <range>.select { |y| is_leap?(y) }
For example,
(1895..1905).select { |y| is_leap?(y) } # => [1896, 1904]
(1995..2005).select { |y| is_leap?(y) } # => [1996, 2000, 2004]
Regards, Morton