Lesson 3 of 10
Conditionals
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
Branching with if and unless, and what counts as false
Explanation
if runs the code inside it when its condition is true, elsif adds another condition that is checked when the ones before it didn't match, else takes everything left over, and end closes the whole chain. Ruby checks the branches in order and runs only the first one whose condition is true, so start with the highest cutoff. And if itself returns the value of the last line in the branch that ran, so you can store its result in a variable directly.
Short conditions have shorter forms. The ternary operator cond ? a : b picks between two values on one line, and you can put the condition at the end of a line like this: puts "Welcome" if logged_in. unless is the opposite of if: it runs its code only when the condition is not true, and it reads more clearly than if !.
Careful if you're coming from Python or JavaScript: in Ruby only two values count as false in a condition, nil and false. 0, "" and an empty array all count as true. So if stock passes even when the stock is zero, and nickname || "Guest" returns the empty string itself. Ask explicitly with stock.zero? and nickname.empty?.
Your task
Work out shipping with an if and elsif chain: 0 if the order is 200 or more, 15 if it's at least 100 but under 200, and 25 otherwise. Use the ternary operator to set status to "In stock" if anything is left in stock, or "Out of stock" if not. Set display_name to nickname, or to "Guest" if it's empty. Then print "Reorder from supplier" when nothing is left in stock, with the condition written as unless at the end of the line.
Checks
6 checks- shipping is 15 for an order of 180
- shipping comes from an if/elsif chain, not a hard-coded value
- status is "Out of stock" because zero is not false in Ruby
- display_name is "Guest" because an empty string is not false either
- The supplier alert was printed
- The alert uses unless at the end of the line