简体   繁体   中英

Retrieve a value from a hash in a hash in an array in a hash

I am trying to get the value of zap in a hash that looks like:

hash = {
         :foo => 1,
         :bar => [{
           :baz => 2,
           :zot => {
             :zap => 3
           }
         }]
       }

hash.dig breaks as soon as it gets to the array.

If it's important, this is a step in an if/elsif/else statement checking for different error messages. (ie elsif zap == 3 )

我会做这样的事情:

hash[:bar].first.dig(:zot, :zap)

I believe you are incorrect, and dig in fact works on any object with a dig method. Dig is defined both for arrays and hashes . Also, if I define a dig method on a custom object:

o = Object.new

def o.dig(*args)
  puts args.inspect
  return :result
end

then when called like so:

{custom_object: o}.dig(:custom_object,1,2,3)
#-> output: [1,2,3]
#=> :result

you can see that dig gets called on o with the remaining arguments ( [1,2,3] ) and returns whatever the custom dig method returns.

What you may have missed is that for arrays, you need to use a numeric index, or dig raises a type error when it gets called on the array. So hash.dig(:bar, 0, :zot, :zap) is what you probably want. (credit to Alex for beating me to the punch).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM