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?
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.
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.
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.
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 = (
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]"}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With