1

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

Joel
  • 4,503
  • 1
  • 27
  • 41
Anh
  • 27
  • 1
  • 6
  • [Ruby 1.8.7 is dead](https://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). You shouldn't be using it for new code. – user229044 Feb 10 '15 at 03:48
  • unfortunately, the project using it. I have no option to change – Anh Feb 10 '15 at 03:56

2 Answers2

4

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]]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • Thanks. Just curiosity, what best performance in Arup and Ryan answer? – Anh Feb 10 '15 at 03:55
  • Nice :) I always forget about little convenience helpers like that. I think @Arup's answer is probably more performant as it does the iterating in C (as that's how `values_at` is defined). My answer does it in Ruby. Probably a tiny tiny difference. – Ryan Bigg Feb 10 '15 at 06:14
  • @RyanBigg You wrote the book? R4IA... WooW! – Arup Rakshit Feb 10 '15 at 06:15
  • Yes that's me :) I had a lot of help from Steve Klabnik and Rebecca Skinner on this new edition. – Ryan Bigg Feb 10 '15 at 23:36
  • @RyanBigg Any chance to help this [issue](https://github.com/spree/spree/issues/6032) ? – Arup Rakshit Feb 11 '15 at 07:50
  • @RyanBigg I have same problem like this question http://stackoverflow.com/questions/28469348/ruby-how-to-retrieve-sum-in-array-group-by-multiple-keys-with-condition-max/ Could you take a look? – Anh Feb 12 '15 at 11:23
  • @Anh If you have a problem.. why did you accept? You can ask people who already tried to help you. – Arup Rakshit Feb 12 '15 at 11:24
  • @RyanBigg I accept before I realize the other problem in Mr Cary's answer. He will answer later. As urgent case, so I bother you. Sorry, if you are busy now. – Anh Feb 12 '15 at 11:34
3

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
Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • We have a direct method --- http://ruby-doc.org/core-2.1.5/Hash.html#method-i-values_at :) and in 1.8.7 too http://ruby-doc.org/core-1.8.7/Hash.html#method-i-values_at – Arup Rakshit Feb 10 '15 at 03:48