Ruby: how to convert a hash to an array

I have a hash containing numbers as such:

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

it needs to be converted to an array, for example:

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

I tried my hash values ​​that got me:

 [0.07398921877505593, 0.07400253683443543, 0.07402917535044515] 

I tried several ways, but I just started learning ruby.

+8
arrays ruby hash
source share
2 answers

try the following:

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

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

 {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 item in the hash, and Hash # keys will give you only the keys. Fortunately, the default to_a behavior is what you are looking for.

+7
source share

All Articles