【问题标题】:How can I set elements of a two dimensional array in ruby?如何在 ruby​​ 中设置二维数组的元素?
【发布时间】:2014-01-01 02:48:11
【问题描述】:

我试过了:

1.9.3-p448 :046 > a=Array.new(7){Array.new(7)}
 => [[nil, nil, nil, nil, nil, nil, nil], 
     [nil, nil, nil, nil, nil, nil, nil], 
     [nil, nil, nil, nil, nil, nil, nil], 
     [nil, nil, nil, nil, nil, nil, nil], 
     [nil, nil, nil, nil, nil, nil, nil], 
     [nil, nil, nil, nil, nil, nil, nil], 
     [nil, nil, nil, nil, nil, nil, nil]]
1.9.3-p448 :047 > a[0,0]='a'
 => "a" 
1.9.3-p448 :048 > a[0,1]='b'                                                                
 => "b" 
1.9.3-p448 :049 > a[0,2]='c'                                                                
 => "c"
1.9.3-p448 :050 > a[1,0]='d'                                                                
 => "d" 
1.9.3-p448 :051 > a[1,1]='e'                                                                
 => "e" 
1.9.3-p448 :052 > a[1,2]='f'                                                                
 => "f" 

我得到了:

1.9.3-p448 :053 > a
 => ["c", "f", [nil, nil, nil, nil, nil, nil, nil], 
               [nil, nil, nil, nil, nil, nil, nil], 
               [nil, nil, nil, nil, nil, nil, nil], 
               [nil, nil, nil, nil, nil, nil, nil], 
               [nil, nil, nil, nil, nil, nil, nil]] 

但我想要

1.9.3-p448 :053 > a
 => ["a","b","c",nil,nil,nil], ["d","e","f", nil, nil, nil, nil], 
               [nil, nil, nil, nil, nil, nil, nil], 
               [nil, nil, nil, nil, nil, nil, nil], 
               [nil, nil, nil, nil, nil, nil, nil], 
               [nil, nil, nil, nil, nil, nil, nil]] 

【问题讨论】:

  • 那不是二维数组。它是一个数组数组。

标签: ruby arrays multidimensional-array


【解决方案1】:

在 Ruby 中,正如@Daniel 指出的那样,访问多维数组元素就像在 C 中一样。

您尝试使用的符号来自例如 Pascal,但与您认为它在 Ruby 中的工作方式不同。它在 Ruby 中的作用是给出一个起始索引和一个计数。

如果你有:

 a = ['a','b','c','d','e','f']

那么a[2,3] 将是:

 ['c','d','e']

这在 Ruby Array class documentation 中有描述。如果您尝试分配给它,Ruby 将相应地动态更改数组。在上面的例子中,如果我这样做:

a[2,3] = 'h'

那么a就会变成:

['a','b','h','f']

或者如果我这样做:

a[2,0] = 'j'

Ruby 在位置 2 插入一个值,现在我得到:

['a','b','j','h','f']

换句话说,为a[2,3] 分配一个值用我分配给它的任何值替换了三个值的子数组。在二维数组的情况下,比如原来的例子,

a[0,0] = 'a'    # Inserts a new first row of array with value 'a'
a[0,1] = 'b'    # Replaces the entire first row of array with 'b'
a[0,2] = 'c'    # Replaces the entire first two rows of array with 'c'
a[1,0] = 'd'    # Inserts a new first row of array with value 'd'
a[1,1] = 'e'    # Replaces the entire second row of array with 'e'
a[1,2] = 'f'    # Replaces the entire second and third rows of array with 'f'

因此,您会得到您所看到的结果。

【讨论】:

    【解决方案2】:

    您当前正在将字母分配给外部数组的范围。这是引用内部数组的语法:

    a[0][0]='a'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-09
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      相关资源
      最近更新 更多