Method: Object#instance_variable_get

Defined in:
object.c

#instance_variable_get(symbol) ⇒ Object

Returns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name.

class Fred
  def initialize(p1, p2)
    @a, @b = p1, p2
  end
end
fred = Fred.new('cat', 99)
fred.instance_variable_get(:@a)    #=> "cat"
fred.instance_variable_get("@b")   #=> 99

Returns:



2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
# File 'object.c', line 2092

static VALUE
rb_obj_ivar_get(VALUE obj, VALUE iv)
{
    ID id = rb_check_id(&iv);

    if (!id) {
	if (rb_is_instance_name(iv)) {
	    return Qnil;
	}
	else {
	    rb_name_error_str(iv, "`%"PRIsVALUE"' is not allowed as an instance variable name",
			      QUOTE(iv));
	}
    }
    if (!rb_is_instance_id(id)) {
	rb_name_error(id, "`%"PRIsVALUE"' is not allowed as an instance variable name",
		      QUOTE_ID(id));
    }
    return rb_ivar_get(obj, id);
}