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

Short Ruby Tip: Guard clauses

Giovanni Benussi
1 min readMay 4, 2017

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

def method
if condition
# code...
end
end

You could use a guard clause to avoid unnecessary nesting:

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

becomes:

def method
return nil unless condition
# return some not nil value
end

2. Don’t execute something if …

def delete_all_data
unless production?
# delete all data from database...
end
end

becomes:

def delete_all_data
return if production?
# delete all data from database...
end

--

--

Giovanni Benussi
Giovanni Benussi

Written by Giovanni Benussi

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

No responses yet