如何在 Ruby 中声明二维数组
我想要一个 Ruby 中的二维数组,我可以像这样访问它:
if @array[x][y] == "1" then @array[x][y] = "0"
问题是:我不知道数组维度的初始大小,并且我增长了数组(使用 << 运算符)。
如何将其声明为实例变量,这样就不会出现这样的错误?
undefined method `[]' for nil:NilClass (NoMethodError)
问题更新:
@array = Array.new {Array.new}
现在对我有用,所以下面马特的评论是正确的!
我刚刚发现收到错误的原因是因为我像这样迭代了数组:
for i in [email protected]
for j in 0..@array[0].length
@array[i][j] ...
这显然是错误的并产生了错误。它必须是这样的:
for i in [email protected]
for j in 0..@array[0].length-1
@array[i][j] ...
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 [email protected]
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 [email protected]
for j in 0..@array[0].length-1
@array[i][j] ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用嵌套哈希的稀疏二维数组的简单实现,
用法:
A simple implementation for a sparse 2-dimensional array using nested Hashes,
Usage:
马特对你的问题的评论是完全正确的。然而,基于您已标记此“conways-game-of-life”的事实,您似乎正在尝试初始化一个二维数组,然后在游戏的计算中使用它。如果您想在 Ruby 中执行此操作,一种方法是:
这将创建一个用零填充的 my_x_size * my_y_size 数组。
此代码的作用是创建一个 x 大小的新数组,然后将该数组的每个元素初始化为 y 大小的另一个数组,并用 0 初始化每个第二个数组的每个元素。
Matt's comment on your question is totally correct. However, based on the fact that you've tagged this "conways-game-of-life", it looks like you are trying to initialize a two dimensional array and then use this in calculations for the game. If you wanted to do this in Ruby, one way to do this would be:
which will create a my_x_size * my_y_size array filled with zeros.
What this code does is to create a new Array of your x size, then initialize each element of that array to be another Array of your y size, and initialize each element of each second array with 0's.
Ruby 的
Array
不提供此功能。要么手动执行:
要么使用哈希:
Ruby's
Array
doesn't give you this functionality.Either you manually do it:
Or you use hashes: