Skip to content

Instantly share code, notes, and snippets.

@ono
Created November 9, 2010 14:05
Show Gist options
  • Save ono/669108 to your computer and use it in GitHub Desktop.
Save ono/669108 to your computer and use it in GitHub Desktop.
class TryChain
attr_reader :obj
def initialize(obj)
@obj = obj
end
def method_missing(sym,*args,&block)
@obj = @obj.respond_to?(sym) ? @obj.send(sym,*args,&block) : nil
self
end
end
class Object
def try(&block)
maybe = TryChain.new(self)
maybe = block.call(maybe)
maybe.obj
end
end
def test_try(obj)
obj.try{|a| a.map(&:capitalize).map{|b| b + "x"} }
end
test_try ["a","b","cc"] #=> ["Ax","Bx","CCx"]
test_try nil #=> nil
test_try ["a","b",nil] #=> NoMethodError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment