Understanding unless in Ruby

I don’t know about you, but Ruby’s unless has always been kind of hard for me to grok, but I’m realizing that’s because I’ve never seen a great use of it, esp. one that made me go, “Oh wow – yeah I’d definitely use unless there vs. an if statement or something else.”

However, the deeper I’ve gotten into Ruby the more I’ve noticed one place where unless really shines – guard statements. Consider the following:

def update_book_title
  return unless book
 
  book.update(title: title)
end

Now there’s a place I would definitely use unless over other control flow constructs. It’s succinct, easy to understand, and honestly a pleasure to both write and read.

Nice job Ruby! 🔴💎

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.