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)
    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-forum.com/.

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

···

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

Alex Wayne 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 (123) 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)
      value*2
    end
    self
  end
end

foo
#=> #<Object:0x2b47ef9898a8>

foo[6]
#=> 12

HTH,
Sebastian

···

--
Jabber: sepp2k@jabber.org
ICQ: 205544826

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

···

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

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-forum.com/\.