在Ruby中使用重载括号[]访问变量 [英] Accessing variables using overloading brackets [] in Ruby

查看:141
本文介绍了在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)

这篇关于在Ruby中使用重载括号[]访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆