如何以数组索引的形式访问访问器?
我有一个类 Foo
,它有多种方法,例如 button_0_0
、button_0_1
、button_0_2
、button_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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)