!Mac OS X-10.15.7!ruby-2.7.1p83
if-elsif-else-end
How to write an if statement
if conditional expression then
processing
elsif conditional expression then
processing
else
processing
end
First determine if it is a multiple of 4
p year = ARGV[0].to_i
if year%4==0 then
p true
else
p false
end
If you enter year, it is true if it is a multiple of 4, otherwise false
$ ruby check_leap.rb 2004
2004
true
Let's try it in 1999
$ ruby check_leap.rb 1999
1999
false
Becomes Leap year conditions are not just once every four years
p year = ARGV[0].to_i
if year%400 == 0
p true
elsif year%100 == 0
p false
elsif year%4 == 0
p true
else
p false
end
When you do this
$ ruby check_leap.rb 1900
1900
false
$ ruby check_leap.rb 2000
2000
true
Became
If you want to test multiple values at once, just make an array and loop
[2004,1999,1900,2000].each do |year|
p year
if year%400 == 0
p true
elsif year%100 == 0
p false
elsif year % 4 == 0
p true
else
p false
end
end
Execution result
$ ruby check_leap_year.rb
2004
true
1999
false
1900
false
2000
true
It's getting longer, so let's use method
def leap?(year)
if year % 400 ==0
p true
elsif year % 100 ==0
p false
elsif year % 4 == 0
p true
else
p false
end
end
[2004,1999,1900,2000].each do |year|
p year
leap?(year)
end
case
case A
when 1 then
processing
when 2 then
processing
else
processing
end
Rewrite the previous code using case
def leap?(year)
case
when year % 400 ==0 ; true
when year % 100 ==0 ; false
when year % 4 ==0 ; true
else ; false
end
end
[2000, 1900, 2004, 1999].each do |year|
p year
p leap?(year)
end
The program has become shorter
Recommended Posts