Delcaring a foo[] method

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

On Thu, Mar 20, 2008 at 4:56 PM, Alex W.
[email protected] 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

Alex W. wrote:

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

 @obj.foo[123]

That’s two method calls: it calls foo() on @obj and then on the
result
of foo(). So you need to define foo to return something that responds to
[].
Like this:

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

foo
#=> #Object:0x2b47ef9898a8

foo[6]
#=> 12

HTH,
Sebastian

David L Altenburg wrote:

class Foo

def
# 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.

Howdy,

On Mar 20, 2008, at 4:56 PM, Alex W. 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 * 2
end

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

So, something like this:

class Foo

def
# 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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs