除了将其转换为数组之外,有没有办法获得有序哈希的第N个键或值?

时间:2021-06-22 15:33:20

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

在Ruby 1.9.x中,我有一个维护其顺序的哈希

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]

2 个解决方案

#1


19  

Try using Hash#keys and Hash#values:

尝试使用Hash#keys和Hash#值:

thirdKey = hsh.keys[2]
thirdValue = hsh.values[2]

#2


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.

如我错了请纠正我。

#1


19  

Try using Hash#keys and Hash#values:

尝试使用Hash#keys和Hash#值:

thirdKey = hsh.keys[2]
thirdValue = hsh.values[2]

#2


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.

如我错了请纠正我。