2

I have an array like this:

['one','three','two','four']

I have a array of hash like this:

[{'three' => {..some data here..} }, {'two' => {..some data here..} }, {:total => some_total }] # etc...

I want to sort the array of hashes by the first array. I know I can do:

array_of_hashes.sort_by{|k,v| k.to_s} to sort them and it will sort by the key 

( and the .to_s to convert :total to a string )

How can I make this happen?

Edit:

I was incorrect about how this is setup, it is actually like this:

{'one' => {:total => 1, :some_other_value => 5}, 'two' => {:total => 2, :some_other_value => 3} }

If I need to put this in a new question, just let me know and I will do that.

Thank you

1
  • what Ruby version do you use? Commented Mar 30, 2011 at 19:49

2 Answers 2

6

similar to ctcherry answer, but using sort_by.

sort_arr = ['one','three','two','four']
hash_arr = [{'three' => {..some data here..} }, {'two' => {..some data here..} }]

hash_arr.sort_by { |h| sort_arr.index(h.keys.first) }
Sign up to request clarification or add additional context in comments.

1 Comment

I got this to work with your solution with a modification: .sort_by{ |k,v| k = 'z' unless sort_list.include?(k); sort_list.index(k)}. I am sure there is a better way, but I don't know it. also I added 'z' to the sort_arr to give it a place stuff that wasn't found.
0

The index method of Array is your friend in this case:

sort_list = ['one','three','two','four']

data_list = [{'three' => { :test => 3 } }, {'two' => { :test => 2 } },  {'one' => { :test => 1 } },  {'four' => { :test => 4 } }]

puts data_list.sort { |a,b|
 sort_list.index(a.keys.first) <=> sort_list.index(b.keys.first)
}.inspect

Resulting in, the same order as the source array:

[{"one"=>{:test=>1}}, {"three"=>{:test=>3}}, {"two"=>{:test=>2}}, {"four"=>{:test=>4}}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.