Ruby, lesson 4
So far every line of your programs has run. Real programs need to choose: charge a child
less than an adult, warn when a battery is low, skip a step that does not apply. Ruby gives
you if, unless and case for that.
Ruby checks each condition from the top. The first one that is true wins, its block runs,
and the rest are skipped. else catches everything that is left. Every if closes with end.
Note the spelling: it is elsif, not elseif or else if.
2 exercises to try what you just read.
| Operator | Meaning |
|---|
== | equal to |
!= | not equal to |
< > | less than, greater than |
<= >= | at most, at least |
Each comparison produces true or false. Remember that = assigns and == compares.
&& (and) is true when both sides are true.|| (or) is true when at least one side is true.! (not) flips true and false.Ruby stops evaluating as soon as it knows the answer. In a && b, if a is false, b is
never looked at.
Ruby has a short rule: only false and nil are falsy. Everything else is truthy,
including 0 and the empty string "". That surprises people coming from other
languages, so keep it in mind.
unless is the opposite of if: the block runs when the condition is false. Use it for
simple negative checks, and avoid pairing it with else, which gets confusing to read.
A short condition can also go at the end of a line. This reads almost like English:
In Ruby, if is an expression: it produces the value of whichever branch ran. You can assign
it directly. For a tiny two-way choice there is also the ternary operator condition ? a : b.
When you compare one value against many options, case is tidier than a long elsif chain.
Each when can hold a single value, several values separated by commas, or a range.
1..5 is a range from 1 to 5 including both ends.
case picks the first when that matches and runs only that branch.
Read a customer's age (an integer) and print the ticket type and price:
| Age | Output |
|---|---|
| 0 to 2 | Free |
| 3 to 12 | Child: $6 |
| 13 to 64 | Adult: $12 |
| 65 and up | Senior: $8 |
For the input 30 the output is Adult: $12. A case with ranges fits this nicely.
A year is a leap year if it is divisible by 4, except years divisible by 100, which are not leap years unless they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not.
Read a year and print <year> is a leap year or <year> is not a leap year.
battery = gets.to_i
if battery < 10
puts "Plug in now!"
elsif battery < 30
puts "Battery low"
else
puts "Battery fine"
endage = 15
has_ticket = true
if age >= 12 && has_ticket
puts "Enjoy the film"
endputs "Game over" if lives == 0
puts "Keep going" unless lives == 0label = if score >= 50 then "pass" else "fail" end
label = score >= 50 ? "pass" : "fail" # same thingcase gets.to_i
when 0 then puts "none"
when 1..5 then puts "a few"
when 6, 7, 8 then puts "several"
else puts "lots"
end2024 is a leap year