将哈希数组转换为数组
我有一个哈希数组,我需要在新数组中使用哈希值。 哈希的arrays看起来像这样,有几千个。
array = [{:code=>"404"}, {:code=>"302"}, {:code=>"200"}]
我试图查看它,但只发现了如何从哈希转换。
我该怎么做呢?
a=[{:code=>"404"}, {:code=>"302"}, {:code=>"200"}] puts a.map{|x|x.values}.flatten.inspect
产量
["404", "302", "200"]
[{:code=>"404"}, {:code=>"302"}, {:code=>"200"}].flat_map(&:values) #⇒ ["404", "302", "200"]
arr =[{:code=>"404"}, {:code=>"302"}, {:code=>"200"}] arr.map { |h| h[:code] } #=> ["404", "302", "200"]
或者,如果密钥的名称(现在:code
)将来可能会更改:
arr.map { |h| h.first.last } #=> ["404", "302", "200"]