如何申报在Ruby中一个二维数组 [英] How to declare a two-dimensional array in Ruby
问题描述
我想在Ruby中二维数组,我可以访问例如像这样的:
如果@array [X] [Y] ==1,则@array [X] [Y] =0
问题是:我不知道数组尺寸的初始大小和我长大的阵列(与<<
运营商)。
我如何把它声明为一个实例变量,所以我得到这样的没有错误?
未定义的方法`[]'的零:NilClass(NoMethodError)
问题更新时间:
@array = {Array.new} Array.new
现在对我的作品,所以下面从马特的评论是正确的!
我刚刚找到了原因,我收到的错误是因为我遍历这样的数组:
因为我在0 .. @ array.length
在为0J .. @数组[0]。长度
@array [I] [J] ...
这是明显的错误,并产生错误。它是这样的:
因为我在0 .. @ array.length-1
在为0J .. @数组[0]。长度-1
@array [I] [J] ...
有关稀疏2维数组的简单实现使用嵌套的哈希值,
类SparseArray
attr_reader:哈希 高清初始化
@hash = {}
结束 DEF [](键)
哈希[关键] || = {}
结束 DEF行
hash.length
结束 alias_method:长度:行
结束
用法:
sparse_array = SparseArray.new
sparse_array [1] [2] = 3
sparse_array [1] [2]#= GT; 3p sparse_array.hash
#=> {1 => {2 =→3}}#
#尺寸
#
sparse_array.length#=> 1
sparse_array.rows#=> 1sparse_array [0]。长度#=> 0
sparse_array [1]。长度#=> 1
I want a twodimensional array in Ruby, that I can access for example like this:
if @array[x][y] == "1" then @array[x][y] = "0"
The problem is: I don't know the initial sizes of the array dimensions and i grow the array (with the <<
operator).
How do I declare it as an instance variable, so I get no error like this?
undefined method `[]' for nil:NilClass (NoMethodError)
QUESTION UPDATED:
@array = Array.new {Array.new}
now works for me, so the comment from Matt below is correct!
I just found out the reason why I received the error was because I iterated over the array like this:
for i in 0..@array.length
for j in 0..@array[0].length
@array[i][j] ...
which was obviously wrong and produced the error. It has to be like this:
for i in 0..@array.length-1
for j in 0..@array[0].length-1
@array[i][j] ...
A simple implementation for a sparse 2-dimensional array using nested Hashes,
class SparseArray
attr_reader :hash
def initialize
@hash = {}
end
def [](key)
hash[key] ||= {}
end
def rows
hash.length
end
alias_method :length, :rows
end
Usage:
sparse_array = SparseArray.new
sparse_array[1][2] = 3
sparse_array[1][2] #=> 3
p sparse_array.hash
#=> {1=>{2=>3}}
#
# dimensions
#
sparse_array.length #=> 1
sparse_array.rows #=> 1
sparse_array[0].length #=> 0
sparse_array[1].length #=> 1
这篇关于如何申报在Ruby中一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!