Saturday, March 01, 2008

ruby try sugar




try is a little snippet for Ruby that extends the Object class so that instead of having to do:


@person ? @person.name : nil


you can instead just do:


@person.try(:name)


Just add the following to your Object class:


class Object
##
# @person ? @person.name : nil
# vs
# @person.try(:name)
def try(method)
send method if respond_to? method
end
end