Li Yongqiang
Li Yongqiang

Reputation: 23

How to make myself def class act as 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 aceess 16 use a[i],etc.

Upvotes: 3

Views: 323

Answers (3)

Aetherus
Aetherus

Reputation: 8888

If you just want brackets, then

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

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

Upvotes: 0

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

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>

See? Ruby is telling us exactly what method we are missing:

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

a[0]
# => 16

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

You can simply 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

Upvotes: 3

Related Questions