在 ruby​​ 中创建哈希数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13725643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:34:34  来源:igfitidea点击:

Creating array of hashes in ruby

rubyarrayshashmap

提问by Chirag Rupani

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

我想在 ruby​​ 中创建一个哈希数组,如下所示:

 arr[0]
     "name": abc
     "mobile_num" :9898989898
     "email" :[email protected]

 arr[1]
     "name": xyz
     "mobile_num" :9698989898
     "email" :[email protected]

I have seen hashand arraydocumentation. 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?

在循环中的上述语句中进行迭代允许我填充arr. 我实际上排成一行,就像["abc",9898989898,"[email protected]"]. 有没有更好的方法来做到这一点?

回答by jboursiquot

Assuming what you mean by "rowofrows" is an array of arrays, heres a solution to what I think you're trying to accomplish:

假设你所说的“rowofrows”是一个数组数组,这是我认为你想要完成的一个解决方案:

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

回答by aelor

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.

这会将哈希插入到数组中。同样,您可以推送更多散列以创建散列数组。

回答by miriamtocino

You could also do it directly within the push method like this:

您也可以直接在 push 方法中执行此操作,如下所示:

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

  1. 首先定义你的数组:

    @shopping_list_items = []

  2. 并向您的列表中添加一个新项目:

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

  3. 这会给你这样的东西:

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