gpt4 book ai didi

ruby - 如何让自己的 def 类充当 ruby​​ 中的数组?

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:23 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com