I’m not a huge fan of Ruby’s ‘unless’ keyword. I mean its nice but it can take some while to get used to. For single line ‘unless’ statements like this:
puts user.name unless user.name.nil?
It’s nice and easy. Here’s how I’d say that in english “Print the user’s name unless the user doesn’t have a name”.
Structuring it the other way is not as intuitive to me:
unless user.name.nil? puts user.name end
Here’s how I’d say that in english “Unless the user doesn’t have a name, print the user’s name”. That doesn’t sound good at all. In everyday language I always put the ‘unless’ at the end of the sentence and not the beginning, its just easier for me to understand.
Why do we even need ‘unless’? Let’s trash it and replace it with something else:
class Object def not_nil? ! nil? end end
Then we can have:
puts user.name if user.name.not_nil? if user.name.not_nil? puts user.name end
That’s much better, ‘unless’ never made it into most of the ‘mainstream’ languages most of us grew up on; so coming into OO scripting languages like ruby it may take some time to get this new keyword.