Delcaring a foo[] method

A

Alex Wayne

I am trying to define a method that you call like this:

@obj.foo[123]

I thought I knew how to do this. I tried to setup the method like so:

def foo[](value)
value * 2
end

But this gives me a syntax error right at that first brace. I could
have sworn this worked before. What am I doing wrong?

ruby 1.8.6
 
L

Lyle Johnson

I am trying to define a method that you call like this:

@obj.foo[123]

I thought I knew how to do this...

For this to work, the "foo" method must return an instance of an
object that defines a "[]" method. So, for example, something like
this:

class IndexableThing
def [](index)
2*index
end
end

class OtherThing
def foo
IndexableThing.new
end
end

obj = OtherThing.new
obj.foo[2] # => returns 4

Hope this helps,

Lyle
 
S

Sebastian Hungerecker

Alex said:
I am trying to define a method that you call like this:

=C2=A0 @obj.foo[123]

That's two method calls: it calls foo() on @obj and then [](123) on the res=
ult=20
of foo(). So you need to define foo to return something that responds to []=
=2E=20
Like this:

def foo()
Object.new.instance_eval do
def [](value)
value*2
end
self
end
end

foo
#=3D> #<Object:0x2b47ef9898a8>

foo[6]
#=3D> 12


HTH,
Sebastian
=2D-=20
Jabber: (e-mail address removed)
ICQ: 205544826
 
D

David L Altenburg

Howdy,

I am trying to define a method that you call like this:

@obj.foo[123]

I thought I knew how to do this. I tried to setup the method like so:

def foo[](value)
value * 2
end


Close. You actually want to override the method named "[]" (and maybe
"[]=").

So, something like this:

class Foo

def [](index)
# logic here
end

def []=(index, value)
# do some stuff
end

end


So, for the call you want to make work:
@obj.foo[123]

@obj.foo needs to return an object with "[]" defined.


HTH,

David
 
A

Alex Wayne

David said:
class Foo

def [](index)
# logic here
end

def []=(index, value)
# do some stuff
end

end

Doh, ok. That makes sense. [] cant be part of a method name unless it
IS the whole method.

Thanks guys.
 

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
473,773
Messages
2,569,594
Members
45,123
Latest member
Layne6498
Top