Ruby:OOP&;二维阵列问题
我需要创建一个二维数组类。我做了一项工作,但发现我的类只是有一个内部二维数组,为了访问元素,我必须编写一个冗余单词“table”:Ruby:OOP&;二维阵列问题,ruby,arrays,oop,inheritance,Ruby,Arrays,Oop,Inheritance,我需要创建一个二维数组类。我做了一项工作,但发现我的类只是有一个内部二维数组,为了访问元素,我必须编写一个冗余单词“table”: class Table attr_accessor :table def initialize(w,h) @table = Array.new(h) h.times do @table << Array.new(w) end end x = Table.new(10,10) x.table[5][6] = 'example
class Table
attr_accessor :table
def initialize(w,h)
@table = Array.new(h)
h.times do @table << Array.new(w)
end
end
x = Table.new(10,10)
x.table[5][6] = 'example'
类表
属性存取器:表
def初始化(w,h)
@表=数组。新建(h)
h、 times do@table也许这会有所帮助:是否有任何特定的原因需要编写自己的数组类?默认情况下,您可以通过提供第二个参数来告诉数组填充新元素的内容:
>> a = Array.new(10, [])
=> [[], [], [], [], [], [], [], [], [], []]
Edit:显然,这种方式会使用对传递对象的引用填充数组,因此一旦您执行a[0][0]=“asd”
,所包含数组的每个第一个元素都会更改。不酷
>> a[0][0] = "asd"
=> "asd"
>> a
=> [["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"]]
要使每个包含的数组都是唯一的,请使用第三种语法,每次给它一个要执行的块-块的结果将用于填充数组:
>> b = Array.new(10) { [] }
=> [[], [], [], [], [], [], [], [], [], []]
>> b[0][0] = "asd"
=> "asd"
>> b
=> [["asd"], [], [], [], [], [], [], [], [], []]
此外,由于ruby阵列的工作方式,甚至不需要定义y轴大小:
>> a = Array.new(5)
=> [nil, nil, nil, nil, nil]
>> a[10]
=> nil
>> a[10] = "asd"
=> "asd"
>> a
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, "asd"]
当您在索引中放入大于当前大小的内容时,数组将自动扩展。所以,只需制作一个包含10个空数组的数组,就可以使用10*n大小的数组。我想这可能就是您想要的。它使用@table
实例变量跟踪内部数组,但不为其公开访问器。定义如下:
class Table
def initialize(row_count, column_count)
@table = Array.new
row_count.times do |index|
@table[index] = Array.new(column_count)
end
end
def []=(row, column, value)
@table[row][column] = value
end
def [](row, column = nil)
if column.nil?
@table[row]
else
@table[row][column]
end
end
def inspect
@table.inspect
end
end
下面是您可以如何使用它:
t = Table.new(2, 5)
t[0,0] = 'first'
t[1,4] = 'last'
t[0][1] = 'second'
puts t[0,0]
puts t.inspect
您可能还想看看数组,而不是将其子类化。是的,我真的想创建一个类,将其内部路由(即方法)与实际算法的逻辑分开,我现在正在研究这个算法。感谢阵列自动调整大小!我不知道