if (conditional expression No.1) then
process No.1
elsif (conditional expression No.2) then
process No.2
else
process No.3
end
case X
when Alpha then
process No.1
when Beta then
process No.2
else
process No.3
end
When tried in 2004, 1999, 1900, 2000, the result is Outputs true, false, false, true
The one using the if-else statement is as follows.
uruu.rb
p year = ARGV[0].to_i
if year % 4 == 0 then
if year % 400 ==0 then
p true
elsif year % 100 ==0 then
p false
else
p true
end
else
p false
end
Execution result
C:\Users\nobua\M1>ruby uruu.rb 2004
2004
true
C:\Users\nobua\M1>ruby uruu.rb 1999
1999
false
C:\Users\nobua\M1>ruby uruu.rb 1900
1900
false
C:\Users\nobua\M1>ruby uruu.rb 2000
2000
true
Next, the one using the case is shown.
uruu2.rb
def leap(year)
case
when year % 400 ==0 ; return true
when year % 100 ==0 ; return false
when year % 4 ==0 ; return true
else ; return false
end
end
year1=2004
year2=1999
year3=1900
year4=2000
p year1
p year2
p year3
p year4
p leap(year1)
p leap(year2)
p leap(year3)
p leap(year4)
Execution result
C:\Users\nobua\M1>ruby uruu2.rb
2004
1999
1900
2000
true
false
false
true
array,each
https://qiita.com/daddygongon/items/a550bde1ed6bff5217d8#caseć§
Recommended Posts