如何在 Ruby 中声明一个二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9144822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:44:43  来源:igfitidea点击:

How to declare a two-dimensional array in Ruby

rubyarraysmultidimensional-arraymatrixconways-game-of-life

提问by kadrian

I want a twodimensional array in Ruby, that I can access for example like this:

我想要一个 Ruby 中的二维数组,我可以像这样访问它:

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] ...

采纳答案by csherin

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

回答by Marc Talbot

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:

马特对你的问题的评论是完全正确的。但是,基于您已经标记了这个“conways-game-of-life”这一事实,您似乎正在尝试初始化一个二维数组,然后在游戏的计算中使用它。如果您想在 Ruby 中执行此操作,一种方法是:

a = Array.new(my_x_size) { |i| Array.new(my_y_size) { |i| 0 }}

which will create a my_x_size * my_y_size array filled with zeros.

这将创建一个 my_x_size * my_y_size 填充零的数组。

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.

这段代码的作用是创建一个 x 大小的新数组,然后将该数组的每个元素初始化为另一个 y 大小的数组,并用 0 初始化每个第二个数组的每个元素。

回答by Marc-André Lafortune

Ruby's Arraydoesn't give you this functionality.

RubyArray没有给你这个功能。

Either you manually do it:

要么您手动执行此操作:

(@array[x] ||= [])[y] = 42

Or you use hashes:

或者你使用哈希:

@hash = Hash.new{|h, k| h[k] = []}
@hash[42][3] = 42
@hash # => {42 => [nil, nil, nil, 42]}