【问题标题】:How to alternatively access accessors as array indices?如何交替访问访问器作为数组索引?
【发布时间】:2009-06-15 16:16:37
【问题描述】:

我有一个类Foo,它有几种方法,如button_0_0button_0_1button_0_2button_1_0等。

我希望能够通过以下语法交替访问这些:

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

我知道我可以创建一个 @button 实例变量并遍历所有 button_* 访问器并以这种方式添加它们,但这似乎有点笨拙,并没有真正遵循做事的“红宝石方式” .

我想知道是否有更简洁的 Rubyish 解决方案来解决这个问题(也许使用 method_missing?)——有谁知道更好的方法吗?

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

【问题讨论】:

    标签: ruby method-missing


    【解决方案1】:
    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]
    

    【讨论】:

    • 不要在 Foo 类中使用method_missing,你不能只做 def button return Button.new(self) end 吗?
    • 是的,我不需要method_missing。我用你的建议更新了代码。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-09-27
    • 2023-03-12
    • 2011-12-24
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多