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 |
class Object
def try(method, default=nil)
if respond_to? method
send(method)
else
default
end
end
class Object
##
# @person ? @person.name : nil
# vs
# @person.try(:name)
def try(method)
send method if respond_to? method
end
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Rails 2 does not have try so I rolled my own. I also included a ptry method for methods that don't like nils :)