Ruby supports numerous ways to construct decision statements:
- if statement
- if modifier
- unless statement
- unless modifier
- case statement
Example: IF Statement in Ruby
score = 219
if score == 300
puts "Perfect game."
elsif score >= 200
puts "Great game"
elsif score >= 150
puts "Good game"
else
puts "Keey practicing"
end
Output:
Great game
Example: Ruby if modifier
$flag = 1
print "Run this code\n" if $flag
print "Run this code too\n" if $flag2
Output:
Run this code
The Ruby if modifier runs the code before it only if the condition is true (in this case when the flag is set/true). Notice how the second output line does not run.
Example: Ruby unless Statement
x = 51
unless x >= 50
puts "x is less than 50"
else
puts "x is greater than 50"
end
Output:
Run this code
The Ruby unless statement executes code if conditional is false. If the conditional is true, code specified in the else clause is executed.