[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Defining a method []=

Brett Kushner

8/20/2006 6:40:00 AM

I have used a method of [] with "def method[](string)". But I can't
figure out how to use[]=.

An array works with []= such as array['string1'] = 'string2' so how
would I write a method like that for my own class?


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

3 Answers

Hal E. Fulton

8/20/2006 6:51:00 AM

0

Brett Kushner wrote:
> I have used a method of [] with "def method[](string)". But I can't
> figure out how to use[]=.
>
> An array works with []= such as array['string1'] = 'string2' so how
> would I write a method like that for my own class?
>
>

Much the same way -- it will have two parameters.

class MyClass
def []=(index,assigned)
# ...whatever...
end
end


Make sense?


Hal


John Johnson

8/20/2006 6:54:00 AM

0

On Sun, 20 Aug 2006 02:40:27 -0400, Brett Kushner
<brettkushner@hotmail.com> wrote:

> I have used a method of [] with "def method[](string)". But I can't
> figure out how to use[]=.
>
> An array works with []= such as array['string1'] = 'string2' so how
> would I write a method like that for my own class?
>
>

def method[]=(index, value)
...
end

Regards,
JJ

--
Using Opera's revolutionary e-mail client: http://www.opera...

Scott Baldwin

8/20/2006 6:55:00 AM

0

On 8/20/06, Brett Kushner <brettkushner@hotmail.com> wrote:
> I have used a method of [] with "def method[](string)". But I can't
> figure out how to use[]=.
>
> An array works with []= such as array['string1'] = 'string2' so how
> would I write a method like that for my own class?
>
>
> --
> Posted via http://www.ruby-....
>
>

You define a method called "[]=".

class Foo
def []= key, value
puts "Setting key '#{key}' to '#{value}'"
end
end

f = Foo.new
f[:hello] = "world"

# Setting key 'hello' to 'world'