如何以数组索引的形式访问访问器?

发布于 2024-07-24 16:32:43 字数 536 浏览 10 评论 0原文

我有一个类 Foo ,它有多种方法,例如 button_0_0button_0_1button_0_2button_1_0 code> 等。

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

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

我知道我可以创建一个 @button 实例变量并迭代所有 button_* 访问器并以这种方式添加它们,但这似乎有点笨拙,并且并没有真正遵循“ruby 方式”做事。

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

(我已经弄清楚了这一点,但我被方括号困住了,因为 [] 在缺少的方法上调用了一个新方法......)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我纯我任性 2024-07-31 16:32:43
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]
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]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文