In Ruby, only false or nil is false, and everything else is true, including 0 and the empty string.
false | true |
---|---|
false, nil | other than that( true,0 ,Empty string etc.) |
if If the conditional expression is matched, the specified process is performed.
if expression[then]
formula...
[elsif expression[then]
formula... ]
...
[else
formula... ]
end
[] Is an optional part.
Be careful if you have experience with other languages because it is elsif (without e) instead of els ** e ** if. The last els ** e ** requires e.
score = 90
if score == 100
puts 'S'
elsif score >= 90
puts 'A'
elsif score >= 80
puts 'B'
else
puts 'C'
end
#Example using then
if score == 100 then
puts 'S'
end
Demonstrates its power when judgment conditions and processing are short! It will be easier to see.
Equation 1?Equation 2:Equation 3
#conditions?In case of ◯:In case of ×
checked = true
puts checked ? "Already" : "Not yet"
#Same meaning as the following sentence.
# puts (if checked then "Already" else "Not yet" end)
unless
Opposite to if. If not. Sentences that can be written with unless can also be written with if, so you can write as you like.
Note that it becomes difficult to understand if it becomes a double negation. Unless and code readability in Ruby | TechRacho-Engineer's "?" To "!"-| BPS Co., Ltd.
There is no elsif. else can be omitted.
unless expression[then]
formula...
[else
formula... ]
end
unless baby?
#Conditional expression is false(false)In the case of
puts "eat rice"
else
puts "Drink milk"
end
case As a guideline for proper use with if, I think that case is more suitable for parallel conditions, but how about it?
I thought it was the same as the switch statement, but it seems to be strictly different ... [I would like to say a few words to those who think that the Ruby case is a switch statement of 〇〇 (language name)](https://melborne.github.io/2013/02/25/i- wanna-say-something-about-rubys-case /)
case [formula]
[when expression[,formula] ...[, `*'formula] [then]
formula..]..
[when `*'formula[then]
formula..]..
[else
formula..]
end
os = "macOS"
case os
when "Windows"
#processing
when "macOS", "Unix"
#Conditions for performing the same processing can be described together
when "Linux"
#processing
else
#processing
end
Control Structure (Ruby 2.7.0 Reference Manual) Operator expression (Ruby 2.7.0 reference manual)
Recommended Posts