Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort hash in ruby according to some custom rules [closed]

Tags:

ruby

hash

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?

like image 648
Gandalf StormCrow Avatar asked Jan 30 '26 20:01

Gandalf StormCrow


2 Answers

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.

like image 76
sawa Avatar answered Feb 01 '26 09:02

sawa


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)

like image 25
LPD Avatar answered Feb 01 '26 09:02

LPD