Stefan Tilkov's Random Stuff

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

Comments

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.