Inline `if` and `unless`

suggest change

A common pattern is to use an inline, or trailing, if or unless:

puts "x is less than 5" if x < 5

This is known as a conditional modifier, and is a handy way of adding simple guard code and early returns:

def save_to_file(data, filename)
  raise "no filename given" if filename.empty?
  return false unless data.valid?

  File.write(filename, data)
end

It is not possible to add an else clause to these modifiers. Conditional modifiers are a poor fit for the main logic. For complex code, use a normal if, elsif, else instead.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents