[英]Ruby on Rails - Get array of values from array of hash with particular order of existing keys
The original array likes this: 原始数组如下所示:
[{:age=>28, :name=>"John", :id=>1}, {:name=>"David", :age=>20, :id=>2, :sex=>"male"}]
Order of existing keys: 现有密钥的顺序:
[:id, :name, :age] or ['id', 'name', 'age']
The result should be: 结果应为:
[[1, "John", 28], [2, "David", 20]]
Thank for teaching me. 谢谢教我
P/s: I am using Ruby 1.8.7 and Rails 2.3.5 P / s:我正在使用Ruby 1.8.7和Rails 2.3.5
Thanks 谢谢
Here is a nice way using #values_at
: 这是使用
#values_at
的好方法:
records = [
{:age=>28, :name=>"John", :id=>1},
{:name=>"David", :age=>20, :id=>2, :sex=>"male"}
]
attributes = [:id, :name, :age]
records.collect { |h| h.values_at(*attributes) }
# => [[1, "John", 28], [2, "David", 20]]
Map all the records and then map the attributes in the order given to return the attributes' values in the specified order. 映射所有记录,然后按照给定的顺序映射属性,以指定的顺序返回属性的值。
records = [
{:age=>28, :name=>"John", :id=>1},
{:name=>"David", :age=>20, :id=>2, :sex=>"male"}
]
attributes = [:id, :name, :age]
records.map do |record|
attributes.map { |attr| record[attr] }
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.