In Ruby, how can I get instance variables in a hash instead of an array?

Totty.js picture Totty.js · May 13, 2010 · Viewed 18.8k times · Source

I have a Ruby class. I want to get an instance variable from an argument to a method in that class. I can do get all of the instance variables as an array:

self.instance_variables

However, I want to get the instance variable named arg, specifically:

class MyClass
  def get_instance_variable(arg)
    hash_of_instance_variables[arg]
  end
end

object.get_instance_variable('my_instance_var')

How do I compute hash_of_instance_variables?

Answer

Yossi picture Yossi · Dec 7, 2011

To create a hash of all instance variables you can use the following code:

class Object
  def instance_variables_hash
    Hash[instance_variables.map { |name| [name, instance_variable_get(name)] } ]
  end
end

But as cam mentioned in his comment, you should use instance_variable_get method instead:

object.instance_variable_get :@my_instance_var