Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使自己的def类在ruby中充当数组?_Ruby - Fatal编程技术网

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

如何使自己的def类在ruby中充当数组?,ruby,Ruby,我该怎么办?然后我可以使用[I]等。你可以简单地使用继承: 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) 类堆 16 你为什么不试试呢?Ruby将帮助您:-) 如果你

我该怎么办?然后我可以使用[I]等。你可以简单地使用继承:

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)
类堆 16
你为什么不试试呢?Ruby将帮助您:-)


如果你只需要括号,那么

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

a[0]
# => 16

我只是从中找到了答案。无论如何,非常感谢。我是ruby的新手。将来我会问很多问题。提前再次感谢。事实上,我更喜欢Mittag的答案。它更清楚。相反,继承可能表现得出乎意料。但也谢谢你。也谢谢你。我更喜欢Mittag'ans。
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)
a[0]
# NoMethodError: undefined method `[]' for #<Heap:0x007f8516286ea8>
class Heap; def [](i) a[i] end end

a[0]
# => 16
class Heap
  def [](n)
    # Retrieve value from nth slot
  end

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