Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash does not contain 'try' method

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?

like image 796
David Weiser Avatar asked Apr 26 '26 10:04

David Weiser


1 Answers

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.

like image 101
Jörg W Mittag Avatar answered Apr 28 '26 23:04

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!