Ankush Kataria
Ankush Kataria

Reputation: 323

How to get value of key or key presence from nested hash?

How do I get the value of a key or the key's presence from a nested hash?

For example:

a = { "a"=> { "b" => 1, "c" => { "d" => 2, "e" => { "f" => 3 } }}, "g" => 4}

Is there any direct method to get the value of "f"? Or is there a method to know the presence of key in the nested hash?

Upvotes: 1

Views: 588

Answers (3)

Alissa H
Alissa H

Reputation: 510

A slightly different version of the answer provided by sawa:

%w[a c e f].inject(a) { |a, key| a.fetch(key, {}) }

The difference is that an empty hash will be returned if a key is not found at any point in the hierarchy, rather than an exception being raised. It is probably better to raise an exception in most cases, but this is an alternative depending on your use case.

Upvotes: 0

user946611
user946611

Reputation:

def is_key_present?(hash, key)
  return true if hash.has_key?(key)
  hash.each do |k, v|
    return true if v.kind_of?(Hash) and is_key_present?(v, key)
  end
  false
end

> is_key_present?(a, 'f')
=> true

Upvotes: 2

sawa
sawa

Reputation: 168111

%w[a c e f].inject(a, &:fetch) # => 3
%w[a c e x].inject(a, &:fetch) # > Error key not found: "x"
%w[x].inject(a, &:fetch) # => Error key not found: "x"

Or, to avoid errors:

%w[a c e f].inject(a, &:fetch) rescue "Key not found" # => 3
%w[a c e x].inject(a, &:fetch) rescue "Key not found"  # => Key not found
%w[x].inject(a, &:fetch) rescue "Key not found"  # => Key not found

Upvotes: 5

Related Questions