This article is related to Part 7 of the Special Lecture on Multiscale Simulation. We will proceed according to Chart Ruby.
This time, we will learn about Ruby conditional branching and Array.each according to Chart type ruby-III (if, case, Array.each by leap year).
Ruby
if-elsif-else-end
if returns the result of the expression evaluated at the end of the clause where the condition is met. [] Is an optional part.
if expression[then]
formula...
[elsif expression[then]
formula... ]
...
[else
formula... ]
end
In Ruby, only false or nil is false, and everything else is true, including 0 and the empty string.
It can also be expressed in a refreshing form.
...formula?formula(true_case) :formula(false_case)
If there is no else
...formula...if expression
You can shorten it like this.
case-when-end
case makes a match judgment for one expression. The value specified in the when clause and the result of evaluating the first expression are compared using the operator ===, and if they match, the body of the when clause is used. Evaluate.
case [formula]
[when expression[,formula] ...[, `*'formula] [then]
formula..]..
[when `*'formula[then]
formula..]..
[else
formula..]
end
In Ruby, arrays are represented by [].
Array.each
each reads the elements in the array in order and assigns them to variables.
[ ... ].each do |variable|
formula
end
The rules for leap years are
――The number of years divisible by 400 is a leap year --The number of years that is not divisible by 400 and is divisible by 100 is normal --If the above conditions are not met, the number of years divisible by 4 is a leap year, otherwise it is a normal year.
According to this rule, a leap? Function is created to determine the leap year of the four years 2000, 1900, 2004 and 1999.
The program and execution result are described below.
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
[2000, 1900, 2004, 1999].each do |year|
p year
leap?(year)
end
It's a little long, so I'll use a case statement to make it refreshing.
def leap?(year)
return 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
> ruby check_leap_year.rb
2000
true
1900
false
2004
true
1999
false
Completed successfully.
Programming Language Ruby Reference Manual Leap Year & # x2013; Wikipedia
Recommended Posts