Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Object#instance_variable_set
[T] (::interned variable, T value) -> T
obj.instance_variable_set(symbol, obj) → obj
obj.instance_variable_set(string, obj) → obj
object.c
View on GitHub ↗
static VALUE
rb_obj_ivar_set_m(VALUE obj, VALUE iv, VALUE val)
{
ID id = id_for_var(obj, iv, instance);
if (!id) id = rb_intern_str(iv);
return rb_ivar_set(obj, id, val);
}
Sets the instance variable named by symbol to the given object. This may circumvent the encapsulation intended by the author of the class, so it should be used with care. The variable does not have to exist prior to this call. If the instance variable name is passed as a string, that string is converted to a symbol.
Example
class Fred def initialize(p1, p2) @a, @b = p1, p2 end end fred = Fred.new('cat', 99) fred.instance_variable_set(:@a, 'dog') #=> "dog" fred.instance_variable_set(:@c, 'cat') #=> "cat" fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
See also
#instance_variables
#is_a?
#instance_variable_get
#itself
also in
4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0