0

I have an array like this:

[
  "temp-1",
  [69.63076923076923, 5.397898451463096],
  "temp-2",
  [70.44, 0.9044335243676014],
  "hum-1",
  [45.199999999999996, 0.09999999999999788],
  "hum-2",
  [43.82, 1.0568822072492268]
]

I want to convert it to a hash with the string as keys and the arrays as the value:

{
  "temp-1" => [69.63076923076923, 5.397898451463096],
  "temp-2" => [70.44, 0.9044335243676014],
  ...
}

What is a clean way to do this?

1 Answer 1

5

You can use Hash[...], here is an example:

=> array = ["temp-1", [69.63076923076923, 5.397898451463096], "temp-2", [70.44, 
0.9044335243676014], "hum-1", [45.199999999999996, 
0.09999999999999788], "hum-2", [43.82, 1.0568822072492268]]
=> Hash[*array]
#> {"temp-1"=>[69.63076923076923, 5.397898451463096], "temp-2"=>[70.44, 0.9044335243676014], "hum-1"=>[45.199999999999996, 0.09999999999999788], "hum-2"=>[43.82, 1.0568822072492268]}
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, to_h requires proper nested pairs.
It's so clean. Damn I love ruby!
...or arr.each_slice(2).to_h.

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.