How to override []= array method?

My class is defined as,

  class Memory < Array

and I need to override the []= method.
I tried something like,

  def []=(address, value)
    self[address] = Word.new(value)
  end

which causes an infinite loop of course: 'stack level too deep'.
How to do it right?

···

--
Posted via http://www.ruby-forum.com/.

Before defining the new method use alias_method to create a copy of the
original one with a different name:

class Memory < Array
  alias_method :set_element, :=

  def = address, value
    set_element address, value
  end
end

I hope this helps

Stefano

···

Il giorno Fri, 20 Apr 2012 16:22:07 +0900 "Gaurav C." <lists@ruby-forum.com> ha scritto:

My class is defined as,

  class Memory < Array

and I need to override the = method.
I tried something like,

  def =(address, value)
    self[address] = Word.new(value)
  end

which causes an infinite loop of course: 'stack level too deep'.
How to do it right?

Use the super keyword. It calls the method by the same name belonging
to a class or module higher in the "inheritance hierarchy".

(Note that "super" and "super()" have different meanings - the second
form calls the method with no arguments, while the first with the same
arguments as passed to your method.)

  def []=(address, value)
    super(address, Word.new(value))
  end

-- Matma Rex

My class is defined as,

class Memory < Array

Please do not do this. Rather use composition to achieve what you want.

and I need to override the = method.

If you do it, you need to override *all* manipulating methods because
otherwise it is not guaranteed that all elements in the Array will be
instances of Word.

Kind regards

robert

···

On Fri, Apr 20, 2012 at 9:22 AM, Gaurav C. <lists@ruby-forum.com> wrote:

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/