[英]Taking values from a Ruby array of hashes
I have an array of hashes: 我有一系列哈希:
a = [{"Key1"=>"Value1", "Key2"=>"Value2"},
{"Key1"=>"Value3", "Key2"=>"Value4"},
{"Key1"=>"Value5", "Key2"=>"Value6"}]
Basically I am trying to get an output with only values and not any keys. 基本上,我试图获取仅包含值而不包含任何键的输出。 Something like this
像这样
['Value1', 'Value2', 'Value3', 'Value4', 'Value5', 'Value6']
Here is the code which I tried. 这是我尝试过的代码。 As
key1
and key2
are the same, I stored both the keys in an array.... 由于
key1
和key2
相同,因此将两个密钥存储在一个数组中。
k = ["key1", "key2"]
for i in 0..a.length
k.each do |key_to_delete|
a[i].delete key_to_delete unless a[i].nil?
end
end
However, this removes all values and I get an empty array. 但是,这将删除所有值,并且我得到一个空数组。 Any help is appreciated.
任何帮助表示赞赏。
You can use Enumerable#flat_map
and fetch values from each hash: 您可以使用
Enumerable#flat_map
并从每个哈希中获取值:
a.flat_map(&:values)
=> ["Value1", "Value2", "Value3", "Value4", "Value5", "Value6"]
This is an answer on the original question. 这是原始问题的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.