Convert array of hashes to array

眉间皱痕 提交于 2020-01-06 22:47:12

问题


I have an array of hashes from which I need the values of the hashes in a new array. The array of hashes look likes this, with a couple thousand of them.

array = [{:code=>"404"}, {:code=>"302"}, {:code=>"200"}]

I have tried to look this up but have only found out how to convert from a hash.

How would I go about doing this?


回答1:


a=[{:code=>"404"}, {:code=>"302"}, {:code=>"200"}] 
puts a.map{|x|x.values}.flatten.inspect

output

["404", "302", "200"]



回答2:


[{:code=>"404"}, {:code=>"302"}, {:code=>"200"}].flat_map(&:values)
#⇒ ["404", "302", "200"]



回答3:


arr =[{:code=>"404"}, {:code=>"302"}, {:code=>"200"}]

arr.map { |h| h[:code] }
  #=> ["404", "302", "200"]

or, if the name of the key (now :code) might change in future:

arr.map { |h| h.first.last }
  #=> ["404", "302", "200"]


来源:https://stackoverflow.com/questions/40066614/convert-array-of-hashes-to-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!