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'


h = {'a' => [title: 'ab', path: 'cd'], 'b' => [title: 'ef', path: 'gh']}
h.select { |_,v| v[0][:title] == 'ef' }.keys
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"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章