簡體   English   中英

使用數組值從數組哈希中獲取鍵

[英]Obtain Key from a Hash of Arrays using array value

我有一個哈希,如下所示:

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

現在說我有一個標題,希望從中獲得鑰匙...

即如果我有“ ef”並想要“ b”

這是我目前正在做的事情,但是似乎很笨拙...

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)

還有其他更好的方法嗎?

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM