Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 597
Chirag Rupani Avatar asked Dec 05 '12 14:12

Chirag Rupani


People also ask

What is array & hash in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.

How do you combine hashes in Ruby?

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.

How do you create a hash in Ruby?

In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.

What is hash array?

An array of hashes in the Perl language stores data that you would like to access in a sequential manner. Each of the array indices has key/value pairs for hashes. The general syntax for arrays that consist of hashes is as shown below: @Arrays = (


1 Answers

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]"}]
like image 144
jboursiquot Avatar answered Oct 13 '22 00:10

jboursiquot