RUBY / CHAPTER 01
Values and expressions
BeginnerRead Ruby’s truth rules and value-producing branches.
By the end of this chapter
- Distinguish nil and false from other values
- Use interpolation without changing the source value
- Treat conditionals as expressions
The idea
Ruby expressions produce values, including if expressions. Variables refer to objects, and method calls request behavior from those objects. Strings support interpolation inside double quotes, while arithmetic follows the operand types. Start by tracing one expression at a time and distinguishing the value it returns from any text it prints. The p method is useful when inspecting strings and collections.
Only nil and false are falsey in Ruby. Zero, an empty string, and an empty array are all truthy, so presence checks are not the same as emptiness checks. Use an explicit predicate such as empty? when the requirement concerns content. A branch can assign its selected result directly, reducing temporary state while keeping the condition and its meaning visible.
count = 0
label = if count
"present"
else
"missing"
end
puts label
puts "Count: #{count}"present Count: 0
Zero is truthy, so the first branch supplies the label. Interpolation constructs text without turning the original count binding into a string.
Try it yourself
Return "empty" for an empty string and "filled" otherwise, without treating zero as false.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING