ruby:如何将哈希转换为数组

时间:2022-02-11 01:59:28

I have a hash that contains numbers as such:

我有一个包含数字的哈希:

{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}

it needs to be converted into an array like:

它需要转换为如下数组:

[[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]]

i tried my hash.values which gets me:

我尝试了我的hash.values让我:

[0.07398921877505593, 0.07400253683443543, 0.07402917535044515]

I have tried multiple ways but i just started learning ruby.

我尝试了多种方法,但我刚开始学习红宝石。

2 个解决方案

#1


16  

try this:

尝试这个:

{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}.to_a
#=> [[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]]

#2


7  

Definitely use the Hash#to_a method, which will produce exactly what you are looking for.

绝对使用Hash#to_a方法,它将生成您正在寻找的内容。

{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}.to_a
=> [[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]] 

Hash#values will give you only the values of each element in the hash, while Hash#keys will give you just the keys. Fortunately, the default behavior of to_a is what you are looking for.

散列#值只给你哈希中每个元素的值,而哈希#键只给你键。幸运的是,to_a的默认行为是您正在寻找的。

#1


16  

try this:

尝试这个:

{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}.to_a
#=> [[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]]

#2


7  

Definitely use the Hash#to_a method, which will produce exactly what you are looking for.

绝对使用Hash#to_a方法,它将生成您正在寻找的内容。

{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}.to_a
=> [[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]] 

Hash#values will give you only the values of each element in the hash, while Hash#keys will give you just the keys. Fortunately, the default behavior of to_a is what you are looking for.

散列#值只给你哈希中每个元素的值,而哈希#键只给你键。幸运的是,to_a的默认行为是您正在寻找的。