[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Delcaring a foo[] method

Alex Wayne

3/20/2008 9:57:00 PM

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

4 Answers

Lyle Johnson

3/20/2008 10:22:00 PM

0

On Thu, Mar 20, 2008 at 4:56 PM, Alex Wayne
<rubyonrails@beautifulpixel.com> wrote:

> 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

Sebastian Hungerecker

3/20/2008 10:25:00 PM

0

Alex Wayne wrote:
> 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: sepp2k@jabber.org
ICQ: 205544826

David L Altenburg

3/20/2008 10:26:00 PM

0

Howdy,

On Mar 20, 2008, at 4:56 PM, Alex Wayne wrote:

> 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


Alex Wayne

3/20/2008 11:25:00 PM

0

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