Lesson contents

Ruby — Using if as an expression

In Ruby, if is an expression. Assign its result to a variable to select a stock label without repeating the assignment in each branch.

A simple example

Follow one branch

  1. Start with n is 2
  2. Do this Is n positive?
  3. Result yes
The condition selects the first branch. Changing the value to zero selects the other branch.
lesson.rb
n = 2
if n > 0
  puts "yes"
else
  puts "no"
end
Output
yes
Advertisements

Classify a stock level

An if expression returns the value of the selected branch. The assignment captures that String. zero? expresses the exact boundary directly.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.

Run the example

Ruby 2.7 or later. Run these commands from the directory containing the example.

ruby lesson.rb
lesson.rb
stock = 3
status = if stock.zero?
           "sold out"
         elsif stock <= 5
           "order soon"
         else
           "in stock"
         end
puts status
Output
order soon

The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.

Try it yourself

Try the boundary values 0, 5, and 6.

Check your answer

They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.

Ruby language documentation

Related tags

  • Ruby
  • conditions
  • branching
  • comparison