Overloading the []-Operator

Hi,

I’m trying to overload the [ ] operator. It works fine for read-only
access:

def
@myValues[acc]
end

However, I’d also need write access. I’ve tried:

def =(value)
@myValues[acc] = value
end

And get a syntax error on the first line. I’d appreciate any help.

Matt

On Thursday 10 July 2008, Matthias Winkelmann wrote:

def =(value)
@myValues[acc] = value
end

And get a syntax error on the first line. I’d appreciate any help.

Matt

def []=(acc, value)

Stefano

On Thu, 2008-07-10 at 19:55 +0900, Matthias Winkelmann wrote:

def =(value)
@myValues[acc] = value
end

And get a syntax error on the first line. I’d appreciate any help.

Matt

irb(main):017:0> class Junk
irb(main):018:1> def initialize ; @myValues = {} ; end
irb(main):019:1> def [] (acc) ; @myValues[acc] ; end
irb(main):020:1> def []= (acc,value) ; @myValues[acc] = value ; end
irb(main):021:1> end
=> nil
irb(main):022:0> a = Junk.new
=> #<Junk:0xb7baa538 @myValues={}>
irb(main):023:0> a[5]
=> nil
irb(main):024:0> a[5]=5
=> 5
irb(main):025:0> a[5]
=> 5
irb(main):026:0>

Stefano C. wrote:

def []=(acc, value)

…because the name of the method is “[]=”, strange though that may seem
to a Ruby newbie!