1

I have an array of arrays:

data = [
 ["Smith", "Bob", "Male"], 
 ["Jim", "Tim", "Male"],   
 ["Welch", "Anne", "Female"]
]

How would I convert it to look like:

data = [
 {:first_name => "Smith", :last_name => "Bob", :gender => "Male"},  
 {:first_name => "Jim", :last_name => "Tim", :gender => "Male"}, 
 {:first_name => "Welch", :last_name => "Anne", :gender => "Female"}
]
2
  • How did you get your AoA input? Can you share code you've tried to do the conversion? Commented Oct 26, 2017 at 1:08
  • 1
    data.map { |f, l, g| { :first_name => f, :last_name => l, :gender => g } } Commented Oct 26, 2017 at 1:17

3 Answers 3

8

You can do something like this:

fields = [:first_name, :last_name, :gender]
data.map {|row| fields.zip(row).to_h }

#=> [{:first_name=>"Smith", :last_name=>"Bob", :gender=>"Male"}, {:first_name=>"Jim", :last_name=>"Tim", :gender=>"Male"}, {:first_name=>"Welch", :last_name=>"Anne", :gender=>"Female"}] 

Keep in mind that this will only work if the elements are in the same order as the fields.

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

Comments

1

Also you could use Struct:

presenter = Struct.new(:first_name, :last_name, :gender)
data.map { |e| presenter.new(*e).to_h }
#=> [{:first_name=>"Smith", :last_name=>"Bob", :gender=>"Male"}, 
#    {:first_name=>"Jim", :last_name=>"Tim", :gender=>"Male"}, 
#    {:first_name=>"Welch", :last_name=>"Anne", :gender=>"Female"}]

Comments

0
fields = [:first_name, :last_name, :gender]
data.map{|d| Hash[fields.zip(d)]}

1 Comment

While this may answer the question, it doesn't provide any context to explain how or why. Consider adding a sentence or two to explain your answer. This may help both the asker of this question, and generations of future coders who come across this answer. :-)

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.