ruby: how to convert hash into array

22,801

Solution 1

try this:

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

Solution 2

Definitely use the Hash#to_a method, which will produce 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 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.

Share:
22,801
user2376068
Author by

user2376068

Updated on May 15, 2020

Comments

  • user2376068
    user2376068 almost 4 years

    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:

    [0.07398921877505593, 0.07400253683443543, 0.07402917535044515]
    

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