try
I continue to like Ruby because of nice little gems like this:
class Object
##
# @person ? @person.name : nil
# vs
# @person.try(:name)
def try(method)
send method if respond_to? method
end
end
This is a single archived entry from Stefan Tilkov’s blog. For more up-to-date content, check out my author page at INNOQ, which has more information about me and also contains a list of published talks, podcasts, and articles. Or you can check out the full archive.
I continue to like Ruby because of nice little gems like this:
class Object
##
# @person ? @person.name : nil
# vs
# @person.try(:name)
def try(method)
send method if respond_to? method
end
end
If you want to implement:
It will be:
ciao jens
Interestingly, this sort of functionality (and the similar idioms using “@person … if @person” and “foo = @person || ” ” remind me a lot of XPath/XQuery, where $x/person is simply the empty sequence if person doesn’t exist.
Probably an artifact of needing different programming methods for programming against content models (where stuff might be missing) as opposed to fixed programming interfaces.