views:

131

answers:

1

I have a class Foo which has several methods like button_0_0, button_0_1, button_0_2, button_1_0, etc.

I would like to be able to access these alternatively via the following syntax:

foo.button[0][1]
foo.button[1][2]
# etc.

I know I could just create a @button instance variable and iterate through all the button_* accessors and add them that way, but that seems a bit kludgy and doesn't really follow the "ruby way" of doing things.

I was wondering if there was a more succinct, Rubyish solution to this problem (maybe by using method_missing?)—Does anyone know a better way of doing this?

(I've figured this out partway, but I get stuck at the square brackets because [] calls a new method on the missing method...)

+3  A: 
class Foo
  def button
    Button.new(self)
  end
  def button_0_1
    "zero-one"
  end
  def button_0_2
    "zero-two"
  end

  private
  class Button
    def initialize(parent)
      @parent           = parent
      @first_dimension  = nil
    end
    def [](index)
      if @first_dimension.nil?
        @first_dimension = index
        self
      else
        @parent.send("button_#{@first_dimension}_#{index}")
      end
    end
  end
end
puts Foo.new.button[0][1]
puts Foo.new.button[0][2]
Subba Rao
Instead of using `method_missing` in class Foo, can't you just do def button return Button.new(self) end?
David Seiler
yes, i dont need method_missing. i updated the code with your suggestion. thanks.
Subba Rao