arthur-net arthur-net - 1 year ago 67
Ruby Question

Order array of hashes by another array

I got 2 arrays one array of hashes another array of keys. I need to make array of hashes to be in same order as array of keys. How can I do it

header = ["header1", "header2", "header3", "header4", "header5"]
record = [{"header4" =>"value4"}, {"header3" =>"value3"}, {"header5"=>"value5"}, {"header1"=>"value1"}, {"header2"=>"value2"}]

I need array record to put in the same order as array the header

record = [{"header1" =>"value1"}, {"header2" =>"value2"}, {"header3"=>"value3"}, {"header4"=>"value4"}, {"header5"=>"value5"}]

Thank you very much to every one for the help. I want to add one more question to this post.
I am trying to use methods suggested below to create CSV document from database. So I want to organise columns in particular order and I have template of this order and this template stored as array of headers but when I doing

csv<< mymodel.attributes.values.sort_by! { |h| header.index(h.keys[0])

It does not work

Answer Source

Array#sort_by! / Enumerable#sort_by accept a block. The return value of the block is used for comparison. For your case, you can use Array#index.

header = ["header1", "header2", "header3", "header4", "header5"]
record = [{"header4" =>"value4"}, {"header3" =>"value3"},
          {"header5"=>"value5"}, {"header1"=>"value1"},
record.sort_by! { |h| header.index(h.keys[0]) }
# => [{"header1"=>"value1"}, {"header2"=>"value2"}, {"header3"=>"value3"},
#     {"header4"=>"value4"}, {"header5"=>"value5"}]