3

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?

Community
  • 1
  • 1
David Weiser
  • 5,190
  • 4
  • 28
  • 35

2 Answers2

12

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?

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
1

try is not part of ruby 1.8.7, though Rails does include it through ActiveSupport. try is part of Object from ruby 1.9+ (afaik).

James Brooks
  • 658
  • 4
  • 5