# Overloading the \[\]-Operator

**URL:** <https://www.ruby-forum.com/t/overloading-the-operator/142693>\
**Category:** Ruby\
**Created:** [July 10, 2008, 12:59pm UTC](https://www.ruby-forum.com/t/overloading-the-operator/142693 "2008-07-10T12:59:30Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![mawi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/eb8c5e/32.png) [@mawi](https://www.ruby-forum.com/u/mawi)\
**Post date:** [July 10, 2008, 12:59pm UTC](https://www.ruby-forum.com/t/overloading-the-operator/142693/1 "2008-07-10T12:59:30Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![mawi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/eb8c5e/32.png) [@mawi](https://www.ruby-forum.com/u/mawi)\
**Post date:** [July 10, 2008, 1:44pm UTC](https://www.ruby-forum.com/t/overloading-the-operator/142693/2 "2008-07-10T13:44:47Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![mawi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/eb8c5e/32.png) [@mawi](https://www.ruby-forum.com/u/mawi)\
**Post date:** [July 10, 2008, 1:12pm UTC](https://www.ruby-forum.com/t/overloading-the-operator/142693/3 "2008-07-10T13:12:30Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![mawi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/eb8c5e/32.png) [@mawi](https://www.ruby-forum.com/u/mawi)\
**Post date:** [July 11, 2008, 1:02pm UTC](https://www.ruby-forum.com/t/overloading-the-operator/142693/4 "2008-07-11T13:02:31Z")

</div>

Stefano C. wrote:

> def []=(acc, value)

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