A little Smalltalk in Ruby: #if_nil and #if_not_nil
November 23rd, 2007
I really like Smalltalk’s ifNil: and ifNotNil:, and up to now, I could not use these in Ruby. Fortunately, Bob Hutchison came to the rescue with A Little Unnecessary Smalltalk Envy.
I immediately copied that to XLsuite and wrote a couple of tests. Here is sample of what the code feels like:
Oh well, no Sam in my database. The code is here:
November 23rd, 2007 at 08:19 AM
Wow! Unit tests! You’ve raised the bar on these little doodads. I’m going to have to start using them in the future. Some of these things, even though tiny are still seriously useful and deserve the tests.
November 23rd, 2007 at 09:22 AM
nice. mind if I steal it? :)
November 23rd, 2007 at 10:15 AM
Would #unless_nil be more idiomatic Ruby than #if_not_nil?
And while I’m being pedantic, how about #if_nil? instead of #if_nil and #unless_nil? instead of #unless_nil …?
Nice technique though.
November 23rd, 2007 at 05:06 PM
why not just do:
Party.find_by_email_address(“sam@gamgee.net”) && puts(“Found Sam!”)
?
January 29th, 2008 at 07:45 PM
@Andy
‘unless’ and ‘if not’ are both widely used in ruby and in this case are equivalent. Just because ‘unless’ is a unique feature of the language doesn’t make it more idiomatic for ruby.
the convention of adding question-marks to the end of methods is to suggest it returns a boolean value, which these do not.
January 31st, 2008 at 02:55 PM
@macournoyer:
I prefer:
puts(“Found Sam!”) unless Party.find_by_email_address(“sam@gamgee.net”).nil?
or for a multi-liner:
unless Party.find_by_email_address(“sam@gamgee.net”).nil? puts(“Found Sam!”) end
June 10th, 2008 at 11:37 PM
@macournoyer: the example could’ve been better. I think the idea is that instead of:
you could do:
or instead of:
you could do: