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.
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