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. Also it is generally not recommended to use conditional modifiers inside the main logic -- For complex code one should use normal if
, elsif
, else
instead.