views:

293

answers:

2

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
+3  A: 

try instance_variable_get instead:

 def [](iv)
     instance_variable_get("@#{iv}")
 end
khelll
Thanks, that worked.
juanmaflyer
+5  A: 

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)

Chuck
Excellent Chuck! I didn't know anything about sending a variable...It also works with instance_variable_getThanks..
juanmaflyer
send works with methods only, attr_accessor adds both setter and getter methods for you, so send basically is calling the getter.
khelll