How do I force my def class to act like an array in ruby?
3 answers
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)
Why don't you just try it? Ruby will help you :-)
a[0]
# NoMethodError: undefined method `[]' for #<Heap:0x007f8516286ea8>
Cm? Ruby tells us which method we are missing:
class Heap; def [](i) a[i] end end
a[0]
# => 16
+2
source to share