Ruby 如何作为数组索引访问访问器?
我有一个类Ruby 如何作为数组索引访问访问器?,ruby,method-missing,Ruby,Method Missing,我有一个类Foo,它有几种方法,比如按钮0\u 0,按钮0\u 1,按钮0\u 2,按钮1\u 0,等等 我希望能够通过以下语法访问这些选项: foo.button[0][1] foo.button[1][2] # etc. 我知道我可以创建一个@button实例变量,然后遍历所有button.*访问器,然后以这种方式添加它们,但这似乎有点笨拙,并没有真正遵循“ruby方式”做事情 我想知道这个问题是否有更简洁、更鲁莽的解决方案(可能通过使用方法\u missing?)-有人知道更好的方法吗
Foo
,它有几种方法,比如按钮0\u 0
,按钮0\u 1
,按钮0\u 2
,按钮1\u 0
,等等
我希望能够通过以下语法访问这些选项:
foo.button[0][1]
foo.button[1][2]
# etc.
我知道我可以创建一个@button
实例变量,然后遍历所有button.*
访问器,然后以这种方式添加它们,但这似乎有点笨拙,并没有真正遵循“ruby方式”做事情
我想知道这个问题是否有更简洁、更鲁莽的解决方案(可能通过使用方法\u missing
?)-有人知道更好的方法吗
(我已经半途而废了,但是我被方括号卡住了,因为
[]
在缺少的方法上调用了一个新方法…而不是在Foo类中使用方法\u缺少
,你不能只做def按钮返回按钮。新(自我)结束吗?是的,我不需要方法\u缺少。我用你的建议更新了代码。谢谢
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]