Ruby — Ternary expressions
Ruby's condition ? yes : no expression selects a single result. The branch containing a calculation is evaluated only when its condition selects it.
A simple example
Choose one value
- Start with n is 2
- Do this Choose by sign
- Result positive
n = 2
puts(n > 0 ? "positive" : "other")
positive
Choose a report value when a sample is missing
Report a whole-number average for a nonempty group and a text label for an empty group. Guard the division where the result is selected. Use zero? explicitly because 0 is truthy in Ruby. The other path computes an integer quotient and converts it for display.
A monitor displays the average of a sensor’s samples. If no sample arrived, show a message before attempting division. Three samples with a total of 18 give an average of 6.
Run the example
Use Ruby 2.6 or later. Run these commands from the directory containing the example.
ruby lesson.rb
[0, 3].each do |count|
label = count.zero? ? 'no samples' : 18.div(count).to_s
puts label
end
no samples 6
The first group has zero samples and displays no samples. In the second group, 18 divided by 3 gives 6.
Try it yourself
What does an observed total of zero with three samples display?
Check your answer
It displays 0. This is a measured zero, whereas the empty group has no average.