I am noticing differences between a hash object within Ruby 1.8.7 and a hash object within Rails 3.0.10.
For example, within the 1.8.7 irb
, I get:
1.8.7 :001 > {}.try(:method)
NoMethodError: undefned method `try' for {}:Hash
from (irb):1```
However, from the 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 try
is defined in Object which is an ancestor of Hash and try
will return nil instead of throwing a NoMethodError.
What am I missing?
This surprises me because I was under the impression that
try
is defined inObject
which is an ancestor ofHash
andtry
will returnnil
instead of throwing aNoMethodError
.What am I missing?
Your impression of which class try
is defined in is correct (Object
). What you are missing is what file it is defined in. It's defined in the ActiveSupport library, not in the Ruby core library.
So, you need to
require 'active_support/core_ext/object/try'
first.