我需要快速初始化一个任意的二维数组,比如:
[
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
]
问:什么样的 Ruby 代码,初始化这样一个数组最简单?
>> arr = Array.new(8, Array.new(8, 0))
=> [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
>> arr[0][0] = 1
=> 1
>> arr
=> [[1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0]]
用 Array.new 创建的这个对象去填充,造成的结果是修改一个数值,所有的内部数组都会被修改。
#6 楼 @yesmeck 正解,刚刚好我今天遇到这样一个需求,在网上找到了这个 http://rubyquicktips.com/post/844746058/how-to-initialize-a-multidimensional-array
顺便推荐这个网站: http://rubyquicktips.com/
arr = []
0.upto(7) do |i|
arr[i] = []
0.upto(7) do |j|
arr[i][j] = 0
end
end
Array.new(8) {Array.new(8, 0)} 好像我之前问过你这个问题,不知道是不是现在的 API 注释清楚了。
new(size=0, obj=nil) new(array) new(size) {|index| block }
Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). 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.
@jjym 上次在群里战过了 对枚举器做 map 不科学啊 而且会做一个隐式的 to_a
map 和 reduce 都是对 vector 的操作 应该写成 ([0]*8).map {[0]*8}
而且内部没必要再 map 了,因为 Fixnum Fixnum objects have immediate value. This means that when they are assigned or passed as parameters, the actual object is passed, rather than a reference to that object.
irb(main):001:0> a = [[0]*8]*8
=> [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
irb(main):002:0> a[0][0] = 1
=> 1
irb(main):003:0> a
=> [[1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0]]