Created
November 9, 2010 14:05
-
-
Save ono/669108 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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