[code="ruby"]
arr =Array.new(3,Array.new(3,-1))
arr[0][0] = 1
arr[0][1] =2
arr[0][2] = 3
i =1
while(i<3)
arr[i][0] = arr[i-1][0]+1
j = 1
while(j<3)
arr[i][j] = arr[i][j-1]+1
j+=1
end
i+=1
end
p arr
[/code]
本意是要打印出这样的数组
结果是这样
[[3, 4, 5], [3, 4, 5], [3, 4, 5]]
能告诉我,这是为什么吗????
我应该说清楚了吧
就是说
[code="ruby"]arr =Array.new(3,Array.new(3,-1)) [/code]这样定义
实际上第二个元素都是一个值对象的引用
然后,
[code="ruby"]arr[i][j] = arr[i][j-1]+1[/code]这个赋值
实际会,改变三个值。
这一点也可以如下验证[code="ruby"]
Array.new(3, Array.new(3,0)).each{|i|p i.object_id}
-616182288
-616182288
-616182288
[[0, 0, 0], [0, 0, 0], [0, 0, 0]].each{|i|p i.object_id}
-616198918
-616198928
-616198938 [/code]
额,,不管是为什么,给你个建议,,不要把ruby写的和c语言一个风格..
至于你要实现的可以这样:
[code="ruby"]
arr=[]
arr[0]=1,2,3.each do |i|
arr[i]=arr[0].map{|m| m+i}
end
p arr
[/code]
结果:[code="ruby"]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
[/code]
更灵活一些的:
[code="ruby"]
def generate_array(n)
arr=Array.new(n)
arr[0]=(1..n).to_a
(0..n-1).each do |i|
arr[i]=arr[0].map{|m| m+i}
end
arr
end
p generate_array(4)
[/code]
结果:
[code="ruby"]
[[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]]
[/code]
严重同意楼上的看法, :lol:
看着也清楚,舒服,不是吗 :P
同时,说说,楼上的为什么不对吧
首先,把arr定义换成
[code="ruby"]arr = Array.new(3){Array.new(3,0)}[/code]
就是你的预期结果了
然后,为什么呢,官方API给了最标准的定义。怎么执行他们说了算啊 :D
[code="ruby"]
Array.new(size=0, obj=nil)
Array.new(array)
Array.new(size) {|index| block }
[/code]
Returns a new array. In the first form, the new array is empty. In the second it is [color=red]created with size copies of obj (that is, size references to the same obj)[/color]. The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element‘s index to the given block and storing the return value.
所以,我们用最有一种方法创建二维数组,那么就没问题啦
其实,我也想说,下次,你如果在ruby上遇到其他,问题,也应该用这样的思路来解决,也许,会对你有帮助。
(⊙o⊙)…
LS你应该试一下再说我的不对...
:o
quote=Hooopo…
LS你应该试一下再说我的不对... [/quote]
我错了, :cry:
我想说楼主,为什么不对,然后打错了,还没法改。。。。
我道歉 :wink:
额,,,我想也是打错了。。。O(∩_∩)O哈哈~ :D