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. 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.

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:



2952
2953
2954
2955
2956
2957
2958
# File 'object.c', line 2952

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);
}