I wrote a simple, ugly nested conditional to achieve the following:
To achieve the following:
Return "true" if the year meets the following conditions:
- Is divisible by four
- AND is not a century year (e.g.) 1900
- UNLESS it is divisible by 400 (e.g. 400, 800, 2000)
I wrote an ugly nested conditional:
if year % 4 == 0
puts "Divisible by four"
if year % 100 == 0
puts "Century year"
if year % 400 == 0
puts "Quad-century year, leap year"
true
else
"Not a Quad-century year, not a leap year"
false
end
else
puts "Not a century year, leap year"
true
end
else
puts "Not divisible by four: not a leap year."
false
end
I tried to achieve the same with a case conditional, but it fails to detect the number 2016 as leap year:
case year
when (year % 4 == 0 && year % 100 != 0)
true
when year % 400
true
when year % 4 != 0
false
end
Two questions:
- What am I doing wrong in my case conditional?
- Is there a better way to achieve this?
Aucun commentaire:
Enregistrer un commentaire