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?

+3


source to share


2 answers


This surprises me because I got the impression that it try

is defined in Object

which is the ancestor Hash

and try

returns nil

instead of throwing NoMethodError

.

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.

+12


source


try

is not included in ruby ​​1.8.7, although Rails includes it via ActiveSupport

. try

is part Object

of ruby ​​1.9+ (afaik).



+1


source







All Articles