Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 409
Totty.js Avatar asked May 13 '10 21:05

Totty.js


People also ask

Can a Ruby module have instance variables?

Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.

How do you check if a variable is hash in Ruby?

Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .

Are instance variables inherited in Ruby?

Instance variables are not inherited.

How do you declare an instance variable in Ruby?

An instance variable in ruby has a name starting with @ symbol, and its content is restricted to whatever the object itself refers to. Two separate objects, even though they belong to the same class, are allowed to have different values for their instance variables.


2 Answers

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
like image 51
Yossi Avatar answered Oct 25 '22 07:10

Yossi


Question is quite old but found rails solution for this: instance_values

This is first answer in google so maybe it will help someone.

like image 34
sufleR Avatar answered Oct 25 '22 08:10

sufleR