Overloading the []-Operator

  • Thread starter Matthias Winkelmann
  • Start date
M

Matthias Winkelmann

Hi,

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

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

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

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

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

Matt
 
S

Stefano Crocco

Hi,

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

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

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

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

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

Matt

def []=(acc, value)

Stefano
 
M

Michael T. Richter

[Note: parts of this message were removed to make it a legal post.]

Hi,

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

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

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

def [](acc)=(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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,166
Messages
2,570,907
Members
47,448
Latest member
DeanaQ4445

Latest Threads

Top