class Heap
attr_accessor :a, :heap_size
def initialnize(a, heap_size)
@a = a
@heap_size = heap_size
end
end
a = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
a = Heap.new(a, a.length-1)
我该怎么办?然后我可以使用 a[i] 等访问 16。
最佳答案
您可以简单地使用继承:
class Heap < Array
attr_accessor :heap_size
def initialize(a, heap_size)
@heap_size = heap_size
super(a)
end
end
a = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
heap = Heap.new(a, a.length-1)
heap[0]
# => 16
关于ruby - 如何让自己的 def 类充当 ruby 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30255000/