If … then … else
With if your program makes decisions. Comparisons: > greater, < less, >= greater or equal, <= less or equal, == equal (two equals signs!), != not equal. Every if block ends with end.
hunger = 9
if hunger > 7
"Time for bacon!"
else
"All good."
endEven if has a value in Ruby: the branch that won. Change hunger to 3 and run the cell again!
More than two cases? elsif (no e in the middle!) checks another condition. Ruby goes through the conditions from top to bottom – the first one that holds wins, all others are skipped:
temperature = 18
if temperature > 25
"Off to the lake!"
elsif temperature > 15
"T-shirt weather"
else
"Grab a sweater!"
endConditions can be combined: && means “and” (both must hold), || means “or” (one is enough), and ! turns a condition around:
hungry = true
tired = false
puts hungry && tired
puts hungry || tired
puts !tired
puts 3 > 2 && 2 > 1And now a Ruby peculiarity that may surprise you: for if, everything counts as true – except false and nil. Even the number 0 and the empty string "" count as true! Try it: put nil, "" and false into value, one after the other.
value = 0
if value
"#{value.inspect} counts as true"
else
"#{value.inspect} counts as false"
end(inspect shows a value the way you would write it in Ruby – with quotes around strings.)
For short cases Ruby has shorthands: an if may stand after a line, unless is the opposite of if, and condition ? yes : no is a whole if/else in one line:
puts "Bacon, please!" if hunger > 7
puts "I'm full." unless hunger > 7
hunger > 7 ? "hungry" : "full"When you compare one value with many possibilities, case/when is tidier than a long elsif chain. when understands ranges, too: 90..100 means “from 90 to 100”:
points = 72
case points
when 90..100 then "Excellent!"
when 50..89 then "Passed"
else "Keep practicing"
endnumber = 7. The cell should yield big if the number is greater than 10, medium if it is greater than 5, and small otherwise – as a value or with puts. Use if, elsif and else. (Then try other numbers!)number = 7
# if ...
case/when and ranges: 90 to 100 points are an "A", 80 to 89 a "B", 70 to 79 a "C", anything below a "D". Store the grade for points in grade.points = 83
# grade = ... # 90 to 100: "A", 80 to 89: "B", 70 to 79: "C", below: "D"