Chirag Rupani
Chirag Rupani

Reputation: 1715

Creating array of hashes in ruby

I want to create an array of hashes in ruby as:

 arr[0]
     "name": abc
     "mobile_num" :9898989898
     "email" :[email protected]

 arr[1]
     "name": xyz
     "mobile_num" :9698989898
     "email" :[email protected]

I have seen hash and array documentation. In all I found, I have to do something like

c = {}
c["name"] = "abc"
c["mobile_num"] = 9898989898
c["email"] = "[email protected]"

arr << c

Iterating as in above statements in loop allows me to fill arr. I actually rowofrows with one row like ["abc",9898989898,"[email protected]"]. Is there any better way to do this?

Upvotes: 7

Views: 35175

Answers (3)

miriamtocino
miriamtocino

Reputation: 31

You could also do it directly within the push method like this:

  1. First define your array:

    @shopping_list_items = []

  2. And add a new item to your list:

    @shopping_list_items.push(description: "Apples", amount: 3)

  3. Which will give you something like this:

    => [{:description=>"Apples", :amount=>3}]

Upvotes: 3

aelor
aelor

Reputation: 11116

you can first define the array as

array = []

then you can define the hashes one by one as following and push them in the array.

hash1 = {:name => "mark" ,:age => 25}

and then do

array.push(hash1)

this will insert the hash into the array . Similarly you can push more hashes to create an array of hashes.

Upvotes: 13

jboursiquot
jboursiquot

Reputation: 1271

Assuming what you mean by "rowofrows" is an array of arrays, heres a solution to what I think you're trying to accomplish:

array_of_arrays = [["abc",9898989898,"[email protected]"], ["def",9898989898,"[email protected]"]]

array_of_hashes = []
array_of_arrays.each { |record| array_of_hashes << {'name' => record[0], 'number' => record[1].to_i, 'email' => record[2]} }

p array_of_hashes

Will output your array of hashes:

[{"name"=>"abc", "number"=>9898989898, "email"=>"[email protected]"}, {"name"=>"def", "number"=>9898989898, "email"=>"[email protected]"}]

Upvotes: 16

Related Questions