Image for post
Image for post
Be safe without messing up too much (source: https://icons8.com)

Short Ruby Tip: Guard clauses

Instead of wrap all of your code in an `if` statement and add unnecessary nesting like this:

def method
if condition
# code...
end
end
def method
return unless condition
# code...
end

Real life examples

1. Return nil if …, otherwise return …

def method
if condition
# return some not nil value
else
nil
end
end
def method
return nil unless condition
# return some not nil value
end
def delete_all_data
unless production?
# delete all data from database...
end
end
def delete_all_data
return if production?
# delete all data from database...
end

Written by

Frontend Developer 👨‍💻 Follow me on Twitter 🐦 https://twitter.com/giovannibenussi

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store