在 Ruby 中创建和迭代二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12874965/
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
Creating and iterating a 2d array in Ruby
提问by Alex
I have very little knowledge about Ruby and cant find a way to create 2d array. Can anyone provide me some snippets or information to get me started?
我对 Ruby 知之甚少,无法找到创建二维数组的方法。谁能为我提供一些片段或信息来帮助我入门?
采纳答案by JunaidKirkire
irb(main):001:0> a = []
=> []
irb(main):002:0> a1 = [1, 2]
=> [1, 2]
irb(main):003:0> a2 = [3, 4]
=> [3, 4]
irb(main):004:0> a.push a1
=> [[1, 2]]
irb(main):005:0> a.push a2
=> [[1, 2], [3, 4]]
irb(main):006:0> a
=> [[1, 2], [3, 4]]
irb(main):007:0> a[0]
=> [1, 2]
irb(main):008:0> a[0][1]
=> 2
回答by simonmenke
a = [[1, 2], [3, 4]]
a.each do |sub|
sub.each do |int|
puts int
end
end
# Output:
# 1
# 2
# 3
# 4
or:
或者:
a = [[1, 2], [3, 4]]
a.each do |(x, y)|
puts x + y
end
# Output:
# 3
# 7
回答by Alfonso Vergara
The easiest way to create a 2d array is by the following:
创建二维数组的最简单方法如下:
arr1 = Array.new(3) { Array.new(3)}
The code above creates a 2D array with three rows and three columns.
上面的代码创建了一个三行三列的二维数组。
Cheers.
干杯。
回答by dpassage
Ruby doesn't have the concept of 2-dimensional arrays like C does. Arrays in Ruby are dynamic -- meaning you can resize them a will. They can contain any object or value in each "slot" - including another Array!
Ruby 没有像 C 那样的二维数组的概念。Ruby 中的数组是动态的——这意味着您可以随意调整它们的大小。它们可以在每个“槽”中包含任何对象或值——包括另一个数组!
In the examples given by @JunaidKirkire and @simonmenke, you have an array which has arrays for its values. You can access the values using the syntax similar to C - but you could also have the case where one slot is an Array and another is just a number, or a String, or a Hash...
在@JunaidKirkire 和@simonmenke 给出的示例中,您有一个数组,其中包含其值的数组。您可以使用类似于 C 的语法访问这些值 - 但您也可能遇到一个插槽是数组而另一个插槽只是数字、字符串或哈希的情况...
You may want to work through a Ruby tutorial to get a better idea of how it works. I like RubyMonkbut there are other good ones out there as well.
您可能希望通过 Ruby 教程来更好地了解它的工作原理。我喜欢RubyMonk,但也有其他好的。
回答by Mohammad Hassan
Addition to the array would follow the following format [row]x[col]:
添加到数组将遵循以下格式 [row]x[col]:
arr1 = Array.new(3) { Array.new(3)}
arr1[0][0] = 4
arr1[0][1] = 5
arr1[1][0] = 6
arr1[1][1] = 7
p arr1
=> [[4, 5, nil], [6, 7, nil], [nil, nil, nil]]
The second constraint is completely arbitrary since without it you can have jagged arrays. Depends on need.
第二个约束是完全任意的,因为没有它你可以拥有锯齿状的数组。视需要而定。
arr1 = Array.new(5) {Array.new()}
arr1[0][0] = 4
arr1[0][1] = 5
arr1[1][0] = 6
arr1[1][1] = 7
p arr1
=> [[4, 5], [6, 7], [], [], []]
arr1 = Array.new(5) {Array.new()}
arr1[0][0] = 4
arr1[0][1] = 5
arr1[1][0] = 6
arr1[1][1] = 7
arr1[1][2] = 8
arr1[1][5] = 9
p arr1
=> [[4, 5], [6, 7, 8, nil, nil, 9], [], [], []]

