Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an instance variable to a class in Ruby

How can I add an instance variable to a defined class at runtime, and later get and set its value from outside of the class?

I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class. A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about.

like image 798
readonly Avatar asked Sep 30 '08 00:09

readonly


People also ask

How do I set 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.

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.

Can class methods access instance variables Ruby?

class . There are no "static methods" in the C# sense in Ruby because every method is defined on (or inherited into) some instance and invoked on some instance. Accordingly, they can access whatever instance variables happen to be available on the callee.

How do you create an instance variable?

Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.


1 Answers

Ruby provides methods for this, instance_variable_get and instance_variable_set. (docs)

You can create and assign a new instance variables like this:

>> foo = Object.new => #<Object:0x2aaaaaacc400>  >> foo.instance_variable_set(:@bar, "baz") => "baz"  >> foo.inspect => #<Object:0x2aaaaaacc400 @bar=\"baz\"> 
like image 139
Gordon Wilson Avatar answered Sep 18 '22 18:09

Gordon Wilson