Yehuda Katz's 10 Favorite Things About Ruby
yehudakatz.com
yehudakatz.com
try was originally defined as:
class Object
def try(method)
send method if respond_to? method
end
end
In Rails it is defined as: class Object
alias_method :try, :__send__
end
class NilClass
def try(*args)
nil
end
end
The following code will exhibit different behavior depending on which version of try you're using: [].try :upcase
For example: # original try
>> [].try :upcase
=> nil
# rails try
>> [].try :upcase
NoMethodError: undefined method `upcase' for []:Array
If Rails uses try internally, and a Rails plugin you've loaded depends on the original version of try, what now? They both behave differently and, presumably, code using them depends on their specific behavior.Also don't forget the dozen or so other versions of try people have added to their own plugins and apps...
I realize there are a range of preferences regarding ways to tackle the problem this is intended to solve, and I'm relatively agnostic about the overall issue, but if the implementation is basically a #send that guards against nil, then it would be unexpected for it to deviate remarkably from #send when dealing with non-nil objects.
One of the libraries is going to break.
In Rails 3, we've made it reasonable to pull in just small pieces of the ActiveSupport library, making it more likely that users will reuse functionality from there rather than reinvent the wheel.
Of course, it's not perfect.
What other people call 'magic', I call not understanding the language and execution environment.
For long-running server-side stuff Ruby would not be my first choice, but for eloquence and scripting capabilities... accept no substitute.
[I am apparently completely wrong here].
irb(main):001:0> class Fixnum
irb(main):002:1> def doit
irb(main):003:2> puts "hey"
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> 2.doit
hey
=> nil
irb(main):007:0>
class Fixnum
def +(other)
42
end
end
3 + 2 => 42