Defining a method []=

B

Brett Kushner

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

Hal Fulton

Brett said:
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
 
J

John Johnson

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
 
S

Scott Baldwin

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?

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'
 

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

No members online now.

Forum statistics

Threads
474,209
Messages
2,571,089
Members
47,689
Latest member
kilaocrhtbfnr

Latest Threads

Top