2
array = [
    [ 1, "name1" ],
    [ 2, "name2" ],
    [ 3, "name3" ],
    [ 4, "name4" ]
]

I want to make this as an array of hashes like this:

array_hash = [{ "id" => 1, "name" => "name1" },  
              { "id" => 2, "name" => "name2" },  
              { "id" => 3, "name" => "name3" },  
              { "id" => 4, "name" => "name4" }]
1
  • Are you sure you want array of hashes instead a single hash? Commented Jan 26, 2016 at 13:41

3 Answers 3

6
array = [
    [ 1, "name1" ],
    [ 2, "name2" ],
    [ 3, "name3" ],
    [ 4, "name4" ]
]
array.map { |e| ['id', 'name'].zip(e).to_h }
#⇒ [
#    {"id"=>1, "name"=>"name1"},
#    {"id"=>2, "name"=>"name2"},
#    {"id"=>3, "name"=>"name3"},
#    {"id"=>4, "name"=>"name4"}
# ]

The only interesting here is Enumerable#zip, that “merges” arrays.

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

Comments

4

I'd use:

array.map { |id, name| { 'id' => id, 'name' => name } }
#=> [{"id"=>1, "name"=>"name1"},
#    {"id"=>2, "name"=>"name2"},
#    {"id"=>3, "name"=>"name3"},
#    {"id"=>4, "name"=>"name4"}]

Comments

0

The .to_h method is new to Ruby 2.x. Here is an alternative for anyone on 1.9.x or lower.

array = [[ 1, "name1" ], [ 2, "name2" ], [ 3, "name3" ], [ 4, "name4" ]]

array.inject([]) { |a, r| a << { id: r[0], name: r[1] } }

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.