解决错误

时间:2011-05-11 12:32:10

标签: ruby

a = [1,0,1]
b = [101101, 0101100, 1011001101, 11000111, 1010110]
i = 0
j = 0
c = []
x = 0
d = []

while x < 5
  c.push b[i].to_s.split('')
  p c
  x = x +1
end

while i < 5
  e = c[i].length
  e = e + 1
  while j < e
    d[i][j] = a[i][j % 3] ^ b[i][j]
    puts d
    j = j + 1
  end
  i = i + 1
end


==> Resolv error line : d[i][j] = a[i][j % 3] ^ b[i][j]
====>  __.rb:18: undefined method `[]=' for nil:NilClass (NoMethodError)

我看不到..

由于

2 个答案:

答案 0 :(得分:2)

如果您想使用d[i][j],则应创建2维:

...
d[i] = []
while j < e
  d[i][j] = a[i][j % 3] ^ b[i][j]
  puts d
  j = j + 1
end
...

但无论如何这都是一个奇怪的代码。如果a[i][j % 3]是一维数组,为什么使用a

答案 1 :(得分:0)

您的变量d只有一个维度,而在第二个while您尝试分配两个维度值d[i][j]。要解决此问题,请将其他字符串添加到while:

d[i] |= []
while j < e
    d[i][j] = a[i][j % 3] ^ b[i][j]
    puts d
    j = j + 1
  end