Inline `if` and `unless`
suggest changeA 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents