Is there any way to get the Nth key or value of an ordered hash other than converting it to an array?
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]
Try using Hash#keys
and Hash#values
:
thirdKey = hsh.keys[2]
thirdValue = hsh.values[2]
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.
精彩评论