In Smalltalk there is the method ifNotNilDo:
It is used like this:
database getUser ifNotNilDo: [:user | Mail sendTo: user ]
On objects that are not nil
the block is executed, passing the object itself as a parameter. The implementation in class UndefinedObject
(Smalltalk's equivalent of Ruby's NilClass
) simply does nothing. That way, if getting the user resulted in a nil
object, nothing would happen.
I am not aware of something similar for Ruby, so I rolled out my own solution. It goes like this:
class Object
def not_nil
yield(self)
end
end
class NilClass
def not_nil
# do nothing
end
end
It could be used like this:
users = {:peter => "[email protected]", :roger => "[email protected]" }
users[:roger].not_nil {|u| Mail.send(u) }
This saves us from accessing the hash twice
Mail.send(users[:roger]) if users[:roger]
... or using a temp-variable:
u = users[:roger]
Mail.send(u) if u
Update:
People are starting to suggest solutions based on hash-operations, and also accessing the hash twice. My question is not directly hash-related.
Imagine instead that the first operation is not a hash-access and also expensive. Like:
RemoteUserRepo.find_user(:roger).not_nil {|u| Mail.send(u) }
(end-of-update)
My questions are:
- Am I wrong to re-invent this idiom?
- Is there something like this (or better) supported in Ruby out-of-the-box?
- Or is there another, shorter, more elegant way to do it?
Mail.send(users[:roger]) if users[:roger]
. Accessing the hash twice shouldn't be that big of a deal in most situations – Miraflores