user2376068
user2376068

Reputation: 207

ruby: how to convert hash into array

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.

Upvotes: 10

Views: 25856

Answers (2)

pcm
pcm

Reputation: 319

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.

Upvotes: 7

Arup Rakshit
Arup Rakshit

Reputation: 118261

try this:

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

Upvotes: 20

Related Questions