Guard Clauses
Clean early returns.
Clean Early Returns
A guard clause is a check at the top of a method that returns early for invalid or edge cases. It keeps the main logic flat and easy to read.
def greet(name)
return "Hello, stranger" if name.nil?
"Hello, #{name}"
end
puts greet(nil)
puts greet("Ada")The Problem: Deep Nesting
Without guards, validations pile up as nested if blocks. The real work ends up buried deep on the right edge of the screen.
def charge(user)
if user
if user[:active]
puts "Charging #{user[:name]}"
end
end
end
charge({ name: "Sam", active: true })