开发者

Accessing variables using overloading brackets [] in Ruby

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 开发者_StackOverflowlike 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


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)


try instance_variable_get instead:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜