Ismail Moghul
Ismail Moghul

Reputation: 2974

Obtain Key from a Hash of Arrays using array value

I have a Hash as follows:

{'a' => [title: 'ab', path: 'cd'], 'b' => [title: 'ef', path: 'gh']}

Now lets say I have one title and wish to get the key from it...

i.e. if I have 'ef' and want 'b'

This is what I'm currently doing, but it seems extremely clunky...

def get_hash_key(hash)
  hash.each do |k, h|
    return k if h[0][:title] == 'ef'
  end
end
h = {'a' => [title: 'ab', path: 'cd'], 'b' => [title: 'ef', path: 'gh']}
get_hash_key(h)

Is there another better way of doing this?

Upvotes: 0

Views: 53

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

h = {'a' => [title: 'ab', path: 'cd'], 'b' => [title: 'ef', path: 'gh']}
  #=> {"a"=>[{:title=>"ab", :path=>"cd"}], "b"=>[{:title=>"ef", :path=>"gh"}]}

h.each_with_object({}) { |(k,v),g| g[v.first[:title]] = k }['ef'] 
  #=> "b"

or

h.each_with_object({}) { |(k,v),g| g[k] = v.first[:title] }.invert['ef']
  #=> "b"

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

h = {'a' => [title: 'ab', path: 'cd'], 'b' => [title: 'ef', path: 'gh']}
h.select { |_,v| v[0][:title] == 'ef' }.keys
# => [
#   [0] "b"
# ]

Upvotes: 2

Related Questions