Ruby on Rails - 从具有特定顺序的现有键的散列数组中获取值数组
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
谢谢
映射所有记录,然后按指定顺序映射属性 return 属性值。
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
这是使用 #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]]
原来的数组是这样的:
[{: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
谢谢
映射所有记录,然后按指定顺序映射属性 return 属性值。
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
这是使用 #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]]