【问题标题】:2D array assigns input to all inner arrays? [duplicate]二维数组将输入分配给所有内部数组? [复制]
【发布时间】:2018-09-01 19:36:20
【问题描述】:

我正在尝试像这样存储和输出方法输入:

Want [ ["email addresses"], ["phone numbers"], ["names"] ]    - >    [["bobsmith@example.com","sallyfield@example.com"],["555-555-5555","111-111-1111"],["Bob Smith","Sally Field"]]

这是我的代码:

    def hash_2_array contacts
    2       # Extract like info from each hash into arrays
    3       stringArr = Array.new(3,Array.new(2))   #=> [ [ nil,nil]  , [nil,nil]  , [nil,nil]  ]
    4       
    5       if contacts.empty?
    6           return nonsense = Array.new(3, Array.new)
    7       else
    8          n=0 #name counter
    9          e=0 #email counter
    10         p=0 #phone counter
    11          contacts.each do |key, value|
    12              stringArr[2][n] = key.to_s              #adds name to array
    13              n+=1
    14              value.each do |key2, value2|
    15                  if key2.to_s.eql?("email")
    16                      stringArr[0][e] = value2.to_s   #adds email address to array
    17                      e+=1
    18                  else
    19                      stringArr[1][p] = value2.to_s   #adds phone number to array
    20                      p+=1
    21                  end
    22              end
    23          end
    24      end
    25      return stringArr
    26  end
    27  
    28  
    29  hash_2_array({:"Bob Smith"=>{:email=>"bobsmith@example.com", :phone=>"555-555-5555"}, :"Sally Field"=>{:email=>"sallyfield@example.com", :phone=>"111-111-1111"}})

返回:

   got: [["555-555-5555", "111-111-1111"], ["555-555-5555", "111-111-1111"], ["555-555-5555", "111-111-1111"]]

这真的很令人困惑,为什么它不只是分配我指定的数组中的索引。我认为这段代码以前有效,但现在它以某种方式被破坏了。任何帮助都会很棒

【问题讨论】:

  • 读者可能想运行你的代码,不管有没有修改。为此,步骤 1 是剪切和粘贴。第 2 步(这不是必需的)是删除所有行号。呈现代码时请不要包含行号、IRB 提示等。

标签: arrays ruby


【解决方案1】:

来自fine manual

new(size=0, default=nil)
new(array)
new(size) {|index|阻止 }
[...]
常见问题
发送第二个参数时,将使用同一个对象作为所有数组元素的值:

a = Array.new(2, Hash.new)
# => [{}, {}]

a[0]['cat'] = 'feline'
a # => [{"cat"=>"feline"}, {"cat"=>"feline"}]

a[1]['cat'] = 'Felix'
a # => [{"cat"=>"Felix"}, {"cat"=>"Felix"}]

如果你想要多个副本,你应该使用每次需要初始化数组元素时使用该块结果的块版本:

a = Array.new(2) { Hash.new }
a[0]['cat'] = 'feline'
a # => [{"cat"=>"feline"}, {}]

当你这样说时:

stringArr = Array.new(3,Array.new(2))

您正在创建一个包含三个元素的数组,但所有这些元素都是完全相同的数组。您想要一个包含三个不同数组作为元素的数组:

stringArr = Array.new(3) { Array.new(2) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 2015-12-06
    相关资源
    最近更新 更多