Accessing variables using overloading brackets [] in Ruby

爱⌒轻易说出口 提交于 2019-12-13 18:08:06

问题


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

回答1:


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)

or

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

(if you want to access the ivar directly)




回答2:


try instance_variable_get instead:

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


来源:https://stackoverflow.com/questions/1903183/accessing-variables-using-overloading-brackets-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!