[英]Ruby on Rails - Get array of values from array of hash with particular order of existing keys
原始數組如下所示:
[{:age=>28, :name=>"John", :id=>1}, {:name=>"David", :age=>20, :id=>2, :sex=>"male"}]
現有密鑰的順序:
[:id, :name, :age] or ['id', 'name', 'age']
結果應為:
[[1, "John", 28], [2, "David", 20]]
謝謝教我
P / s:我正在使用Ruby 1.8.7和Rails 2.3.5
謝謝
這是使用#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]]
映射所有記錄,然后按照給定的順序映射屬性,以指定的順序返回屬性的值。
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.