[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Overloading the []-Operator

Matthias Winkelmann

7/10/2008 10:56:00 AM

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
--
Posted via http://www.ruby-....

3 Answers

Stefano Crocco

7/10/2008 10:57:00 AM

0

On Thursday 10 July 2008, Matthias Winkelmann wrote:
> 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


Michael T. Richter

7/10/2008 11:08:00 AM

0

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

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

> 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>

--
Michael T. Richter <ttmrichter@gmail.com> (GoogleTalk:
ttmrichter@gmail.com)
I'm not schooled in the science of human factors, but I suspect surprise
is not an element of a robust user interface. (Chip Rosenthal)

Dave Bass

7/11/2008 10:58:00 AM

0

Stefano Crocco wrote:
> def []=(acc, value)

...because the name of the method is "[]=", strange though that may seem
to a Ruby newbie!
--
Posted via http://www.ruby-....