1

I have the following data like this:

fields = ["player_id", "name", "team", "player_id", "name", "team", "player_id", "name", "team"]
values = ["001", "Pound", "Monstars", "002", "Bang", "Monstars", "003", "Jordan", "Looney Tunes"]

I want to create an array of hashes, so the data will look like this:

[{"player_id"=>"001", "name"=>"Pound", "team"=>"Monstars"}, {"player_id"=>"002", "name"=>"Bang", "team"=>"Monstars"}, {"player_id"=>"003", "name"=>"Jordan", "team"=>"Looney Tunes"}]

In my quest to improve, I think I'm still doing more steps than necessary:

sliced_fields = fields.each_slice(3).to_a
=> [["player_id", "name", "team"], ["player_id", "name", "team"], ["player_id", "name", "team"]]

sliced_values = values.each_slice(3).to_a
=> [["001", "Pound", "Monstars"], ["002", "Bang", "Monstars"], ["003", "Jordan", "Looney Tunes"]]

new_array = sliced_values.map { |i| Hash[sliced_fields[sliced_values.index(i)].zip(i)] }
=> [{"player_id"=>"001", "name"=>"Pound", "team"=>"Monstars"}, {"player_id"=>"002", "name"=>"Bang", "team"=>"Monstars"}, {"player_id"=>"003", "name"=>"Jordan", "team"=>"Looney Tunes"}]

Is there an easier way to accomplish this?

2
  • Your desired output doesn't make sense. You want three hashes of identical information? Commented Jun 5, 2017 at 22:28
  • @theTinMan sorry, I edited the desired result, and realized my solution produced identical information like you said, so removed that too. Commented Jun 5, 2017 at 23:06

1 Answer 1

1

You were pretty close. zip first, then each_slice:

fields.zip(values).each_slice(3).map(&:to_h)

See it on repl.it: https://repl.it/I7S3

Sign up to request clarification or add additional context in comments.

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.