1

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

2 Answers 2

8

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)

Sign up to request clarification or add additional context in comments.

2 Comments

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

try instance_variable_get instead:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.