Ruby If Else
An if statement is a test that chooses which lines run. Ruby writes the choices with if, elsif and else and closes them with end.
If, elsif and else
The tests run from the top. The first test that passes runs its block, and the rest are skipped.
score = 75
if score >= 90
puts "Top grade"
elsif score >= 60
puts "Pass"
else
puts "Try again"
endOnly false and nil fail
Even 0 passes a test in Ruby. The nil block never prints its line.
if 0
puts "Zero still counts as true"
end
if nil
puts "This line never prints"
endUnless as the mirror word
unless runs its block when the test is false. Here raining is false, so the block runs.
raining = false
unless raining
puts "Go outside"
endA ternary test
A question mark and a colon pick between two values. The passing value is saved into result.
score = 72
result = score >= 60 ? "Pass" : "Fail"
puts resultA modifier if
A short test can sit at the end of a line. The line runs only when the test passes.
door_open = true
puts "Come in" if door_openExample
score = 48
if score >= 90
puts "Excellent"
elsif score >= 60
puts "Pass"
else
puts "Keep practicing"
end
puts "Score checked" if score > 0Key points
- Use if to run a block when its test is true.
- Use elsif to try another test when the first test fails.
- Use else to run a block when every test fails.
- end closes an if statement.
- Only false and nil fail a test.
- unless runs a block when its test is false.
- A ternary test picks one of two values in a single line.
- A modifier if puts its test at the end of a line.
In this example, score is 48. The first test asks whether 48 is at least 90, and it fails. The elsif test asks whether 48 is at least 60, and it fails too. The else block runs and prints Keep practicing. The last line has a modifier if, and its test passes, so it prints Score checked.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
Along with false, which value fails a test in Ruby?