从一系列哈希:
response = [
{"label"=>"cat", "name"=>"kitty", "id"=>189955},
{"label" => "dog", "name"=>"rex", "id" => 550081}
]
有没有办法写出类似的东西:
response.name.kitty
检索包含此值的哈希:
{"label"=>"cat", "name"=>"kitty", "id"=>189955}
答案 0 :(得分:4)
你可以这样做 -
response.select{|x| x["name"] == "kitty"}.first
答案 1 :(得分:3)
使用Proc
response = [{"label"=>"cat", "name"=>"kitty", "id"=>189955},
{"label" => "dog", "name"=>"rex", "id" => 550081}]
finder = Proc.new {|k, v| response.find {|r| r[k] == v} }
然后
finder.call('name', 'rex')
# => {"label"=>"dog", "name"=>"rex", "id"=>550081}
finder.call('label', 'cat')
# => {"label"=>"cat", "name"=>"kitty", "id"=>189955}
答案 2 :(得分:1)
如果您使用 Rails - 只需使用 .pluck
array_of_hashes = [
{ name: "Kate", city: "Minsk", country: "Belarus", id: 1 },
{ name: "Mike", city: "New York", country: "USA", id: 2 },
{ name: "Aleh", city: "Warsaw", country: "Poland", id: 3},
]
>> array_of_hashes.pluck(:name)
>>
>> [ "Kate", "Mike", "Aleh" ]
答案 3 :(得分:0)
如果需要,您还可以传递多个条件:
response = [
{"label"=>"cat", "name"=>"kitty", "id"=>189955},
{"label"=>"cat", "name"=>"kitty", "id"=>189956},
{"label"=>"cat", "name"=>"kitty", "id"=>189957},
{"label"=>"cat", "name"=>"meow", "id"=>189957},
{"label" => "dog", "name"=>"rex", "id" => 550081},
{"label" => "dog", "name"=>"tommy", "id" => 550082},
{"label" => "dog", "name"=>"rex", "id" => 550083}
]
> response.select{|h| h["label"] == "cat" && h["name"] == "kitty" && h["id"] == 189955}
=> [{"label"=>"cat", "name"=>"kitty", "id"=>189955}] # returns array of selected hashes
> response.find{|h| h["label"] == "cat" && h["name"] == "kitty" && h["id"] == 189955}
=> {"label"=>"cat", "name"=>"kitty", "id"=>189955} # returns first match element