Skip to content

Instantly share code, notes, and snippets.

@soumyaray
Last active August 29, 2015 14:16
Show Gist options
  • Save soumyaray/03cf3c6c73b289639b20 to your computer and use it in GitHub Desktop.
Save soumyaray/03cf3c6c73b289639b20 to your computer and use it in GitHub Desktop.
Ruby: unless conditional

Ruby: Unless conditional

Yes, unless is pretty much syntactic sugar for if !

It may seem a bit weird if you are used to if ! but it actually reads much nicer.

Take a look:

unless results_found()
  puts "No results found"
  return nil
end

also:

return nil unless results_found()

However, there are places where unless only makes things more confusing:

unless results_found()
  return nil
else
  puts "everything looks good!"
end

In that last case, for example, it takes time to think what else means when its the opposite of unless. How should we solve this then? To find out, read this longer writeup about unless in Ruby: http://www.railstips.org/blog/archives/2008/12/01/unless-the-abused-ruby-conditional

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment