在 Ruby 中使用重载括号 [] 访问变量
嗨,我想做以下事情。我只是想重载 [] 方法以便访问实例变量...我知道,这根本没有多大意义,但我想这样做是出于一些奇怪的原因:P
它将是这样的...
class Wata
attr_accessor :nombre, :edad
def initialize(n,e)
@nombre = n
@edad = e
end
def [](iv)
self.iv
end
end
juan = Wata.new('juan',123)
puts juan['nombre']
但这会引发以下错误:
override.rb:11:in `[]': undefined method 'iv' for # (NoMethodError)
我该怎么做?
编辑
我也找到了这个解决方案:
def [](iv)
eval("self."+iv)
end
Hi i want to do the following. I simply want to overload the [] method in order to access the instance variables... I know, it doesn't make great sense at all, but i want to do this for some strange reason :P
It will be something like this...
class Wata
attr_accessor :nombre, :edad
def initialize(n,e)
@nombre = n
@edad = e
end
def [](iv)
self.iv
end
end
juan = Wata.new('juan',123)
puts juan['nombre']
But this throw the following error:
overload.rb:11:in `[]': undefined method 'iv' for # (NoMethodError)
How can i do that?
EDIT
I have found also this solution:
def [](iv)
eval("self."+iv)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
变量和消息位于不同的命名空间中。为了将变量作为消息发送,您需要将其定义为:(
如果您想通过访问器获取它)
或
(如果您想直接访问 ivar)
Variables and messages live in a different namespace. In order to send the variable as a message, you'd need to define it as either:
(if you want to get it through an accessor)
or
(if you want to access the ivar directly)
尝试
instance_variable_get
代替:try
instance_variable_get
instead: