10

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.

2 Answers 2

20

try this:

{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}.to_a
#=> [[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]]
Sign up to request clarification or add additional context in comments.

Comments

7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.