Of Mice and Men


Improved ‘try()’

Posted in Ruby by Anders Engström on the March 2nd, 2008

I recently discovered the nice ‘try()’ hack that chris@ozmm.org created.

It has some resemblance to my Array#to_proc - so I though that I would try to create an extended ‘try()’ :)

It works with “nested methods” and supports a default return value.

Here we go:

class Object
  def try(*args)
      options = {:default => nil}.merge(args.last.is_a?(Hash) ? args.pop : {})
      target = self # Initial target is self.
      while target && mtd = args.shift
        target = target.send(mtd) if target.respond_to?(mtd)
      end

      return target || options[:default]
  end
end


class Person
  attr_accessor :name
  attr_accessor :address

end
class Address
  attr_accessor :street
end

def print_info(person, default = nil)
  puts <<-END
    ==============================================================
    Name: #{person.try(:name, :default => default)}
    Street: #{person.try(:address, :street, :default => default)}
  END
end

@person = Person.new
@person.name = "Frank Black"
@person.address = Address.new
@person.address.street = "xyz"
print_info(@person)

@person.address = nil
print_info(@person)
print_info(@person, "No Info Registered")