说我有这样的数据哈希:
7
每个哈希都是这样的
data = [{..}, {..}, {..}]
现在如何获得仅包含某些键/值或多个键的哈希数组。如果我想要新的包含城市的哈希数组,那就拿城市吧。
我知道,我可以手动循环和过滤,但有一个我缺少的内置方法。
答案 0 :(得分:1)
map
会有所帮助:
original_array_of_hashes.map do |hash|
{ city: hash[:city] }
end
如果您正在使用Rails,slice
方法将可用:
original_array_of_hashes.map do |hash|
hash.slice(:city)
end
对于多个键:
# without 'slice'
original_array_of_hashes.map do |hash|
{ key_one: hash[:key_one], key_two: hash[:key_two] }
end
# with 'slice'
original_array_of_hashes.map do |hash|
hash.slice(:key_one, :key_two)
end
答案 1 :(得分:1)
arr = [{ :city => 'Paris', :country => 'France', :pop => 2240001 },
{ :city => 'Bardelona', :country => 'Spain', :pop => 1600002},
{ :city => 'Vancouver', :country => 'Canada', :pop => 603503 }]
def some_keys(arr, *keys_to_keep)
arr.map { |h| h.select { |k,_| keys_to_keep.include? k } }
end
some_keys (arr)
#=> [{}, {}, {}]
some_keys(arr, :city)
#=> [{:city=>"Paris"}, {:city=>"Bardelona"}, {:city=>"Vancouver"}]
some_keys(arr, :city, :pop)
#=> [{:city=>"Paris", :pop=>2240001},
# {:city=>"Bardelona", :pop=>1600002},
# {:city=>"Vancouver", :pop=>603503}]
some_keys(arr, :city, :country, :pop)
#=> [{:city=>"Paris", :country=>"France", :pop=>2240001},
# {:city=>"Bardelona", :country=>"Spain", :pop=>1600002},
# {:city=>"Vancouver", :country=>"Canada", :pop=>603503}]