I have an array like this:
["Is", "Gandalf", "The", "Gray", "Insane"]
and I want to sort a hash according to the position of the key in the array. For example, I would like to sort:
{:count=>21, "Is"=>19, "Gandalf"=>1, "Gray"=>0, "Insane"=>1, "The"=>5}
into this:
{"Is"=>19, "Gandalf"=>1, "The"=>5, "Gray"=>0, "Insane"=>1, :count=>21}
Another example would be sorting this:
{:count=>3, "Is"=>11, "Insane"=>22, "Gray"=>0, "Gandalf"=>12, "The"=>2}
into this:
{"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>12, "Insane"=>22, :count=>3}
How would one do that?
class Hash
def sort_by_array a; Hash[sort_by{|k, _| a.index(k) || length}] end
end
will work for the first example:
a = ["Is", "Gandalf", "The", "Gray", "Insane"]
{:count=>21, "Is"=>19, "Gandalf"=>1, "Gray"=>0, "Insane"=>1, "The"=>5}.sort_by_array(a)
# => {"Is"=>19, "Gandalf"=>1, "The"=>5, "Gray"=>0, "Insane"=>1, :count=>21}
However, it will not work with your second example because the result you expect for the second one is not just sorting, but also requires changing the value for "Gray":
{:count=>3, "Is"=>11, "Insane"=>22, "Gray"=>0, "Gandalf"=>12, "The"=>2}.sort_by_array(a)
# => {"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>0, "Insane"=>22, :count=>3}
# You wanted
# => {"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>12, "Insane"=>22, :count=>3}
Since it is not clear where the value 12 for "Gray" comes from, your question cannot be answered in a way that satisfies your second example.
I would suggest, convert it to an array, by populating the array in the order you require. Then you can access the array itself by using that array or then converting that array to hashmap.
http://x3ro.de/ruby-19-array-hash/
One link discussing the similar lines is ,
How to sort not simple hash (hash of hashes)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With