如何选择访问访问器作为数组索引?

时间:2009-06-15 16:16:37

标签: ruby method-missing

我有一个班级Foo,其中包含多种方法,例如button_0_0button_0_1button_0_2button_1_0等。

我希望能够通过以下语法来替换它们:

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

我知道我可以创建一个@button实例变量并遍历所有button_*访问器并以这种方式添加它们,但这看起来有些笨拙而且并不真正遵循“ruby方式”做事。

我想知道是否有一个更简洁,Rubyish解决这个问题的方法(也许是通过使用method_missing?) - 有没有人知道更好的方法呢?

(我已经想到了这一点,但我被卡在方括号上,因为[]在缺少的方法上调用了一个新方法......)

1 个答案:

答案 0 :(得分:3)

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]
相关问题