94

Possible Duplicate:
Ruby: Nils in an IF statement
Is there a clean way to avoid calling a method on nil in a nested params hash?

Let's say I try to access a hash like this:

my_hash['key1']['key2']['key3']

This is nice if key1, key2 and key3 exist in the hash(es), but what if, for example key1 doesn't exist?

Then I would get NoMethodError: undefined method [] for nil:NilClass. And nobody likes that.

So far I deal with this doing a conditional like:

if my_hash['key1'] && my_hash['key1']['key2'] ...

Is this appropriate, is there any other Rubiest way of doing so?

Community
  • 1
  • 1
Nobita
  • 23,519
  • 11
  • 58
  • 87
  • The accepted answer mentions every possible method except the correct one for Ruby 2.3+ : http://ruby-doc.org/core-2.3.1/Hash.html#method-i-dig – Eric Duminil Jan 08 '17 at 22:13

3 Answers3

189

There are many approaches to this.

If you use Ruby 2.3 or above, you can use dig

my_hash.dig('key1', 'key2', 'key3')

Plenty of folks stick to plain ruby and chain the && guard tests.

You could use stdlib Hash#fetch too:

my_hash.fetch('key1', {}).fetch('key2', {}).fetch('key3', nil)

Some like chaining ActiveSupport's #try method.

my_hash.try(:[], 'key1').try(:[], 'key2').try(:[], 'key3')

Others use andand

myhash['key1'].andand['key2'].andand['key3']

Some people think egocentric nils are a good idea (though someone might hunt you down and torture you if they found you do this).

class NilClass
  def method_missing(*args); nil; end
end

my_hash['key1']['key2']['key3']

You could use Enumerable#reduce (or alias inject).

['key1','key2','key3'].reduce(my_hash) {|m,k| m && m[k] }

Or perhaps extend Hash or just your target hash object with a nested lookup method

module NestedHashLookup
  def nest *keys
    keys.reduce(self) {|m,k| m && m[k] }
  end
end

my_hash.extend(NestedHashLookup)
my_hash.nest 'key1', 'key2', 'key3'

Oh, and how could we forget the maybe monad?

Maybe.new(my_hash)['key1']['key2']['key3']
xavdid
  • 5,092
  • 3
  • 20
  • 32
dbenhur
  • 20,008
  • 4
  • 48
  • 45
  • You can also try the monadic gem, which has a Maybe (and other monads) which help with handling exceptions – Piotr Zolnierek May 04 '12 at 05:03
  • What are your thoughts on using `rescue nil` at the end of the statement? – jakeonrails May 17 '13 at 18:46
  • @jakeonrails `rescue nil` is almost always evil. 1) it can capture and silently discard an exception you weren't aware could be thrown; 2) exceptions are computationally expensive flow control -- one should only use them for exceptional behavior, not expected behavior. – dbenhur May 17 '13 at 20:24
  • 7
    You can use `dig` method for hash after Ruby 2.3, http://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig – LYu Nov 10 '16 at 18:11
  • Or https://www.google.com/search?q=ruby+keypath – sites Dec 14 '16 at 20:44
  • You can use dig method for hash *and Array* since Ruby 2.3 – azerty Feb 20 '17 at 18:57
  • `my_hash.dig` will fail if `my_hash` is `nil`. Consider using the safe navigation operator instead or combined with `.dig` as: `my_hash&.dig(:key1, :key2, :key3)` or `my_hash&.key1&.key2&.key3`. – thisismydesign Sep 11 '17 at 15:29
  • 2
    The syntax of the safe navigator operator on hashes in my previous comment is incorrect. The correct syntax is: `my_hash&.[]('key1')&.[]('key2')&.[]('key3')`. – thisismydesign Sep 18 '17 at 15:23
6

You could also use Object#andand.

my_hash['key1'].andand['key2'].andand['key3']
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
5

Conditions my_hash['key1'] && my_hash['key1']['key2'] don't feel DRY.

Alternatives:

1) autovivification magic. From that post:

def autovivifying_hash
   Hash.new {|ht,k| ht[k] = autovivifying_hash}
end

Then, with your example:

my_hash = autovivifying_hash     
my_hash['key1']['key2']['key3']

It's similar to the Hash.fetch approach in that both operate with new hashes as default values, but this moves details to the creation time. Admittedly, this is a bit of cheating: it will never return 'nil' just an empty hash, which is created on the fly. Depending on your use case, this could be wasteful.

2) Abstract away the data structure with its lookup mechanism, and handle the non-found case behind the scenes. A simplistic example:

def lookup(model, key, *rest) 
    v = model[key]
    if rest.empty?
       v
    else
       v && lookup(v, *rest)
    end
end
#####

lookup(my_hash, 'key1', 'key2', 'key3')
=> nil or value

3) If you feel monadic you can take a look at this, Maybe

Dorian
  • 22,759
  • 8
  • 120
  • 116
inger
  • 19,574
  • 9
  • 49
  • 54