简体   繁体   中英

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

Thanks

Here is a nice way using #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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM