Creating array of hashes in ruby

30,202

Solution 1

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

Solution 2

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.

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

Share:
30,202
Chirag Rupani
Author by

Chirag Rupani

Tech Stack: C#, ASP.NET, ASP.NET core, ReactJS, T-SQL, Microsoft Azure, Entity Framework, JavaScript, Typescript, Html, CSS, Angular (latest Version), RXJS, Vue.js, Xunit, MSTest, Jasmine, Moq, JSON, Web API, UWP, WPF Interests: Agile, TDD, Progressive Web Apps, Reactive programming and continuous delivery

Updated on July 09, 2022

Comments

  • Chirag Rupani
    Chirag Rupani almost 2 years

    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?