在Ruby中使用重载括号[]访问变量

问题描述:

我想做以下事情.我只是想重载[]方法以访问实例变量...我知道,这根本没有什么意义,但是出于某些奇怪的原因,我想这样做:P

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

会是这样的...

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']

但这会引发以下错误:

overload.rb:11:in'[]':#(NoMethodError)的未定义方法'iv'

overload.rb:11:in `[]': undefined method 'iv' for # (NoMethodError)

我该怎么做?

编辑

我也找到了这种解决方案:

I have found also this solution:

def [](iv)
    eval("self."+iv)
end

变量和消息位于不同的命名空间中.为了将变量作为消息发送,您需要将其定义为:

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:

def [](iv)
    send iv
end

(如果您想通过访问器获取它)

(if you want to get it through an accessor)

def [](iv)
    instance_variable_get "@#{iv}"
end

(如果您想直接访问ivar)

(if you want to access the ivar directly)