如何使我自己的def类在ruby中充当数组?

时间:2015-05-15 08:33:11

标签: ruby

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)

我该怎么办?然后我可以使用[i]等等。

3 个答案:

答案 0 :(得分:3)

您可以简单地使用继承:

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

答案 1 :(得分:2)

class Heap
  attr_accessor :a, :heap_size
  def initialize(a, heap_size)
    self.a, self.heap_size = a, heap_size
  end
end

a = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
a = Heap.new(a, a.length-1)

为什么不试试? Ruby会帮助你: - )

a[0]
# NoMethodError: undefined method `[]' for #<Heap:0x007f8516286ea8>

请参阅? Ruby正在告诉我们我们缺少什么方法:

class Heap; def [](i) a[i] end end

a[0]
# => 16

答案 2 :(得分:0)

如果你只想要括号,那么

class Heap
  def [](n)
    # Retrieve value from nth slot
  end

  def []=(n, value)
    # Set value to the nth slot
  end
end