The hash does not contain a "try" method
I notice the differences between a hash object in Ruby 1.8.7 and a hash object in Rails 3.0.10.
For example, within 1.8.7 irb
I get:
1.8.7 :001 > {}.try(:method)
NoMethodError: undefned method `try' for {}:Hash
from (irb):1```
However, from 3.0.10 rails console I get:
1.8.7 :003 > {}.try(:method_x)
NoMethodError: undefined method `method_x' for {}:Hash
from (irb):3:in `try'
from (irb):3
This surprises me because I was under the impression that it try
is defined in Object which is the ancestor of Hash and try
will return no instead of throwing NoMethodError.
What am I missing?
source to share
This surprises me because I got the impression that it
try
is defined inObject
which is the ancestorHash
andtry
returnsnil
instead of throwingNoMethodError
.What am I missing?
Your impression of which class is try
defined in the correct ( Object
). What you are missing is the file in which it is defined. It is defined in the ActiveSupport library, not in the main Ruby library.
So you need
require 'active_support/core_ext/object/try'
the first.
source to share