【问题标题】:Creating array of hashes in ruby在 ruby​​ 中创建哈希数组
【发布时间】:2012-11-23 10:06:27
【问题描述】:

我想在 ruby​​ 中创建一个哈希数组:

 arr[0]
     "name": abc
     "mobile_num" :9898989898
     "email" :abc@xyz.com

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

我看过hasharray 文档。在我发现的一切中,我必须做点什么 喜欢

c = {}
c["name"] = "abc"
c["mobile_num"] = 9898989898
c["email"] = "abc@xyz.com"

arr << c

在循环中按照上述语句进行迭代允许我填写arr。我实际上排了一行,比如["abc",9898989898,"abc@xyz.com"]。有没有更好的方法来做到这一点?

【问题讨论】:

  • 你能澄清一下你的问题吗:我实际上是用一行像 ["abc",9898989898,"abc@xyz.com"]

标签: ruby arrays hashmap


【解决方案1】:

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

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

将输出您的哈希数组:

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

【讨论】:

  • 甚至更短,array_of_hashes = array_of_arrays.collect{|each|Hash[%w{name number email}.zip(each)]}
  • 不错的 akuhn。我喜欢这样。
【解决方案2】:

你可以先定义数组为

array = []

然后您可以将哈希值一一定义如下并将它们推送到数组中。

hash1 = {:name => "mark" ,:age => 25}

然后做

array.push(hash1)

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

【讨论】:

    【解决方案3】:

    你也可以直接在 push 方法中这样做:

    1. 首先定义你的数组:

      @shopping_list_items = []

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

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

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

      =&gt; [{:description=&gt;"Apples", :amount=&gt;3}]

    【讨论】:

      猜你喜欢
      • 2015-04-19
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 2022-01-10
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      相关资源
      最近更新 更多