Created
July 31, 2011 04:11
-
-
Save jasonLaster/1116375 to your computer and use it in GitHub Desktop.
Try methods
This file contains hidden or 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
def double(num) | |
return num * 2 | |
end | |
puts "TRY" | |
puts nil.try(:to_s, 0) #=> 0 | |
puts 5.try(:to_s, 0) #=> "5" | |
puts | |
puts "PTRY" | |
puts "Hello ".ptry('double', "") #=> "Hello Hello" | |
puts "Hello ".ptry("Object.double", "") #=> "Hello Hello" | |
puts nil.ptry(:double, "").inspect #=> "" |
This file contains hidden or 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 Object | |
def try(method, default=nil) | |
return default if self.class == NilClass | |
obj = self | |
obj.send(method) | |
end | |
def ptry(method, default=nil) | |
return default if self.class == NilClass | |
param = self | |
klass = Object | |
klass, method = method.split('.') if method[/\./] | |
klass.send(method, param) | |
end | |
end |
Author
jasonLaster
commented
Aug 1, 2011
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment