[英]Traverse Nested Ruby Hash With Array of Keys
給定具有n級嵌套值的哈希,字段名稱和路徑
contact = {
"Email" => "bob@bob.com",
"Account" => {
"Exchange" => true,
"Gmail" => false,
"Team" => {
"Closing_Sales" => "Bob Troy",
"Record" => 1234
}
}
}
field = "Record"
path = ["Account", "Team"] #Must support arbitrary path length
如何定義一個方法來檢索路徑末尾的字段值。
def get_value(hash, field, path)
?
end
get_value(contact, "Record", ["Account", "Team"])
=> 1234
您可以使用Array#inject
:表示hash['Account']['Team']
, return_value_of_inject['Record']
:
def get_value(hash, field, path)
path.inject(hash) { |hash, x| hash[x] }[field]
end
get_value(contact, field, path) # => 1234
順便說一句, get_value(contact, ['Account', 'Team', 'Record'])
怎么樣?
def get_value2(hash, path)
path.inject(hash) { |hash, x| hash[x] }
end
get_value2(contact, ['Account', 'Team', 'Record']) # => 1234
或get_value(contact, 'Account.Team.Record')
def get_value3(hash, path)
path.split('.').inject(hash) { |hash, x| hash[x] }
end
get_value3(contact, 'Account.Team.Record') # => 1234
讓我們將“字段”視為“路徑”的最后一個元素。 那就簡單了
def grab_it(h, path)
h.dig(*path)
end
grab_it contact, ["Account", "Team", "Record"]
#=> 1234
grab_it contact, ["Account", "Team", "Rabbit"]
#=> nil
grab_it(contact, ["Account", "Team"]
# => {"Closing_Sales"=>"Bob Troy", "Record"=>1234}
grab_it contact, ["Account"]
#=> {"Exchange"=>true, "Gmail"=>false, "Team"=>{"Closing_Sales"=>"Bob Troy",
# "Record"=>1234}}
Hash#dig在v2.3中添加了。
def get_value(contact, field, path)
path.inject(contact) {|p, j| p.fetch(j, {}) }.fetch(field, nil)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.