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.

try

Stefan Tilkov,

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
On December 17, 2008 9:00 AM, Jens said:

If you want to implement:

@person ? @person.name : nil

It will be:

class Object
def try(method)
send method
end
end

class NilClass
def try(method)
nil
end
end

ciao jens

On December 17, 2008 10:08 AM, Martin Probst said:

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.