Inline if / unless
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 41 of 56.
Ruby lets you put if and unless at the end of a single statement, as a one-line modifier. It reads almost like English.
puts "Adult" if age >= 18
puts "Save your work" unless savedThis is the same as:
if age >= 18
puts "Adult"
end
unless saved
puts "Save your work"
endThe inline form shines for guard-style checks at the top of a method, or for one-off conditional updates inside a loop:
return if name.nil? || name.empty?
counts = Hash.new(0)
words.each do |w|
counts[w] += 1 unless w.start_with?("#")
endLike the ternary, use inline modifiers for short statements. If the body would be more than a single line, write a real if block instead.
Challenge
EasyRead a comma-separated list of integers. For each number, print one line, but only when the number is non-zero:
- Print
positive: <n>ifn > 0 - Print
negative: <n>unlessn >= 0
Both lines must use the inline modifier form (no if block, no else). After the loop, print Skipped zeros: <count>, where the count is the number of zeros, also computed without an if block (use count).
For input 3,-2,0,5,0, the output is:
positive: 3
negative: -2
positive: 5
Skipped zeros: 2Cheat sheet
Ruby allows if and unless as inline modifiers at the end of a single statement:
puts "Adult" if age >= 18
puts "Save your work" unless savedUseful for guard clauses or simple conditional updates:
return if name.nil? || name.empty?
counts[w] += 1 unless w.start_with?("#")Use inline modifiers only for single-line bodies; use a full if block for anything longer.
Try it yourself
numbers = gets.chomp.split(",").map(&:to_i)
# TODO: print using inline `if` / `unless` for each number
# TODO: print Skipped zeros: <n> using count
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier