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
- Start with n is 2
- Do this Is n positive?
- Result yes
n = 2
if n > 0
puts "yes"
else
puts "no"
end
yes
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.
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
stock = 3
status = if stock.zero?
"sold out"
elsif stock <= 5
"order soon"
else
"in stock"
end
puts status
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.