Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get the Nth key or value of an ordered hash other than converting it to an array?

Tags:

ruby

In Ruby 1.9.x I have a hash that maintains its order

hsh = {9=>2, 8=>3, 5=>2, 4=>2, 2=>1}

Is there a way to get say the key of the third element other than this:

hsh.to_a[2][0]
like image 897
Jeremy Smith Avatar asked Jun 12 '11 16:06

Jeremy Smith


2 Answers

Try using Hash#keys and Hash#values:

thirdKey = hsh.keys[2]
thirdValue = hsh.values[2]
like image 172
Jacob Relkin Avatar answered Oct 25 '22 07:10

Jacob Relkin


Why do you use hash instead of an array? The array fits perfect for ordered collections.

array = [[9, 2], [8, 3], [5, 2], [4, 2], [2, 1]]
array.each { |pair| puts pair.first }

Sorting of arrays is very simple, ultimately.

disordered_array = [[4,2], [9,2], [8,3], [2,1], [5,2]] 
disordered_array.sort { |a,b| b <=> a }
=> [[9, 2], [8, 3], [5, 2], [4, 2], [2, 1]]

Correct me if I'm wrong.

like image 33
kyrylo Avatar answered Oct 25 '22 09:10

kyrylo