Creating an array of hashes in ruby

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

arr[0] "name": abc "mobile_num" :9898989898 "email" : abc@xyz.com arr[1] "name": xyz "mobile_num" :9698989898 "email" : abcd@xyz.com 

I saw hash and array documentation. In everything I found, I have to do something like

 c = {} c["name"] = "abc" c["mobile_num"] = 9898989898 c["email"] = " abc@xyz.com " arr << c 

Iteration, as in the above instructions in the loop, allows you to fill in arr . I actually rowofrows with one line, like ["abc",9898989898," abc@xyz.com "] . Is there a better way to do this?

+4
source share
3 answers

Assuming what you mean by "rowofrows", this is an array of arrays, this is the solution that I think you are trying to execute:

 array_of_arrays = [["abc",9898989898," abc@xyz.com "], ["def",9898989898," def@xyz.com "]] 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 

Print an array of hashes:

 [{"name"=>"abc", "number"=>9898989898, "email"=>" abc@xyz.com "}, {"name"=>"def", "number"=>9898989898, "email"=>" def@xyz.com "}] 
+7
source

you can first define the array as

 array = [] 

then you can define the hashes one by one and follow them in an array.

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

and then do

 array.push(hash1) 

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

+9
source

You can also do this directly in the push method, for example:

  • First define your array:

    @shopping_list_items = []

  • And add a new item to your list:

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

  • Which will give you something like this:

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

+1
source

All Articles