How can I sort this array of hashes using a secondary array of strings?
I have an array of hashes that looks like this:
user_array = [<#Hashie::Mash id="1" name="Ben">, <#Hashie::Mash id="2" name="Scott">, <#Hashie::Mash id="3" name="David">]
And I also have an array that contains IDs pulled from an external source:
freq_array = ["1","2","2","3","2","3"]
I need to use freq_array
to order user_array
, so that the user whose ID appears the most in freq_array
is first in the user_array
. So based on the above freq_array
, user_array
would be
user_array = [<#Hashie::Mash开发者_开发问答 id="2" name="Scott">, <#Hashie::Mash id="3" name="David">, <#Hashie::Mash id="1" name="Ben">]
What is the best way to do this? Thanks for reading.
EDIT: I got the format of the user_array hashes wrong. Have corrected.
user_array.sort_by { |user| freq_array.count(user["id"]) * -1 }
精彩评论