Lesson 7 of 23 · Ruby 3.2
Choose with conditions
Choose an action by comparing values with if, elsif and case.
Learn
Comparisons such as ==, !=, < and >= produce true or false. Use if to run code when a condition is true, elsif to try another condition, and else for the remaining situation. Ruby checks these branches in order and runs only the first matching branch. For a single action, you can put the condition last: puts "Ready" if ready == true.
Only false and nil count as false in a condition; even 0 and an empty string count as true. Use == to compare values. A single = assigns a value.
Use case with when to choose among named values. For the string choices here, each when tests whether its value matches the case value. An else branch handles an unrecognized choice.
Example
temperature = 18
if temperature < 10
puts "Wear a coat"
elsif temperature < 20
puts "Bring a jacket"
else
puts "Wear a light shirt"
endExperiment
A parcel is accepted only below the weight limit. Predict the decision at weight 5. Then change the rule to accept the limit too: edit the comparison and test both cases.
Predict the response. Change action to "cancel", then to "help", and follow which branch handles each request.