How do I force my def class to act like an array in 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)

      

what should I do? Then I can use 16 using [i] etc.

+3


source to share


3 answers


You can just use inheritance:



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

      

+3


source


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


If you just want parentheses then

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

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

      

0


source







All Articles