Method: Object#instance_variable_set

Defined in:
object.c

#instance_variable_set(symbol, obj) ⇒ Object #instance_variable_set(string, obj) ⇒ Object

Sets the instance variable named by symbol to the given object, thereby frustrating the efforts of the class’s author to attempt to provide proper encapsulation. 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.

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\">"

Overloads:

  • #instance_variable_set(symbol, obj) ⇒ Object

    Returns:

  • #instance_variable_set(string, obj) ⇒ Object

    Returns:



2913
2914
2915
2916
2917
2918
2919
# File 'object.c', line 2913

static VALUE
rb_obj_ivar_set(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);
}