7

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?

1
  • 1
    Can you clarify this bit of your question: I actually rowofrows with one row like like ["abc",9898989898,"[email protected]"] Commented Dec 5, 2012 at 14:42

3 Answers 3

16

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]"}]
Sign up to request clarification or add additional context in comments.

2 Comments

Or even shorter, array_of_hashes = array_of_arrays.collect{|each|Hash[%w{name number email}.zip(each)]}
Nice one akuhn. I like that.
13

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.

Comments

3

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}]

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.