Skip to content

Instantly share code, notes, and snippets.

@hiendinhngoc
Created May 26, 2015 10:00
Show Gist options
  • Save hiendinhngoc/6a930ca6a74a21427064 to your computer and use it in GitHub Desktop.
Save hiendinhngoc/6a930ca6a74a21427064 to your computer and use it in GitHub Desktop.
how to sort a hash base on order of an array
  • It is very easy to sort a hash base on the order of an existed array, we can do this by this code:
hash.sort_by{|k, v| arr.index(k)}
  • And if you want to sort an array of array based on the order of another array:
arr2.sort_by { |e| arr1.index(e[0]) }
#the other way
arr2.sort_by { |element| arr1.index(element.first) }
#the more other way
arr2.values_at(*arr2.map { |str,_| arr1.index(str) })
#one more other way
hash_object = objects.each_with_object({}) do |obj, hash| 
  hash[obj.object_id] = obj
end

[1, 2, 3, 4, 5].map { |index| hash_object[index] }
#see, so suprising!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment