tags:

views:

65

answers:

2

How would I use the parameter value as the instance variable name of an object?

This is the object

Class MyClass    
    def initialize(ex,ey)
      @myvar = ex
      @myothervar = ey
    end
end

I have the following method

def test(element)
  instanceofMyClass.element  #this obviously doesnt work
end

How can I have the test method return either myvar or myothervar value depending on the element parameter. I don't want to write an if condition though, I want to pass myvar or myother var via element to the object instance if possible.

+4  A: 
def test(element)
  instanceofMyClass.send(element.to_sym)  
end

You'll get a missing method error if instanceofMyClass doesn't respond to element.

EmFi
To be clear about the difference between EmFi's method and mine: This one requires you to have a reader method for the instance variable and goes through that while mine accesses it directly.
Chuck
The to_sym is not needed btw. send accepts strings.
sepp2k
Perfect, thank you all "instanceofMyClass.send(element)" does it beautifully. Since I already have a reader, this one seems to be the cleanest/easiest.
eakkas
I included the to_sym to help ensure that a proper method missing error is generated, in the event the argument of element doesn't evaluate to a string.
EmFi
+3  A: 
def test(element)
  instanceofmyclass.instance_variable_get element
end

test :@myvar # => ex
test :@myothervar # => ey
Chuck
I think this one is the nice clean one.
johannes
To be perfectly honest, I'd use `send` if we're talking a public property (as EmFi's case assumes) — that way, we play nice with overrides. This is just more of a general answer to the question asked, which was about instance variables in general.
Chuck