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(book, title)
return unless book.present?
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! 🔴💎