7th

Various conditions

how to fill in if-else

if (conditional expression No.1) then
 process No.1

elsif (conditional expression No.2) then
 process No.2

else
 process No.3

end

How to fill in a case

case X
when Alpha then
 process No.1

when Beta then
 process No.2

else
 process No.3

end

Theme 1 Leap year determination program

Leap year determination method

  1. A leap year is a number of years divisible by 4 A year that meets the condition of 2.1 and is divisible by 100 is not a leap year. A leap year is a year that meets the conditions of 3.1 and is divisible by 400.

When tried in 2004, 1999, 1900, 2000, the result is Outputs true, false, false, true

program

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

References

https://qiita.com/daddygongon/items/a550bde1ed6bff5217d8#case恧


Recommended Posts