Skip to content

Instantly share code, notes, and snippets.

@leejarvis
Created March 25, 2012 19:37
Show Gist options
  • Save leejarvis/2199260 to your computer and use it in GitHub Desktop.
Save leejarvis/2199260 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class TryProxy
def initialize(object)
@object = object
end
def method_missing(meth, *args, &block)
if @object.respond_to?(meth)
@object.__send__(meth, *args, &block)
elsif @object.nil?
nil
else
super
end
end
end
class Object
def try
TryProxy.new(self)
end
end
p "foo".try.chomp("o") #=> "fo"
p nil.try.chomp("o") #=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment