简体   繁体   中英

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" :abc@xyz.com

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

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"] = "abc@xyz.com"

arr << c

Iterating as in above statements in loop allows me to fill arr . I actually rowofrows with one row like ["abc",9898989898,"abc@xyz.com"] . Is there any better way to do this?

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.

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,"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

Will output your array of hashes:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM