From: "Josep M. Bach" Date: 2011-03-31T20:13:09+09:00 Subject: Dereferencing instance variables vs local variables/methods ------=_Part_1106_9070286.1301569887779 Content-Type: multipart/alternative; boundary="----=_Part_1107_15220505.1301569887791" ------=_Part_1107_15220505.1301569887791 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit Hello, I think I don't agree/understand how instance variables work in ruby. For example, when invoking a regular local variable and its name is not defined, it raises appropriately a NameError: >> a >> => NameError: undefined local variable or method `a' for main:Object But when you do: >> @a >> # => nil This is not a bug, but intended behavior, as we can see in rb_ivar_get method: VALUE rb_ivar_get (obj, Id) VALUE obj; ID id; { VALUE val; switches (TYPE (obj)) { case T_OBJECT: case T_CLASS: case T_MODULE: if (ROBJECT (obj) ->Iv_tbl && St_lookup (ROBJECT (obj) ->Iv_tbl, Id, &val) ) return val; break; default: if (FL_TEST (obj, FL_EXIVAR) || rb_special_const_p (obj)) return generic_ivar_get (obj, Id) ; break; } *rb_warning ("instance variable %s not initialized", Rb_id2name (id)); return Qnil;* } (variable.c) Why should Ruby issue a warning and return nil instead of just raising an error? There's probably a good reason for that but I can't see it. ------=_Part_1107_15220505.1301569887791 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Hello,

I think I don't agree/understand how instance var= iables work in ruby.

For example, when invoking a = regular local variable and its name is not defined, it raises appropriately= a NameE= rror:

>> a
>> =3D> NameErro= r: undefined local variable or method `a' for main:Object
<= div>
=
But when you do:

>> @a
&g= t;> # =3D> nil

This is not a bug, but = intended behavior, as we can see in rb_ivar_get method:
VALUE
 rb_ivar_get (obj,  Id)
 VALUE obj;
 ID id;
 {
 VALUE val;

 switches (TYPE (obj)) {
 case T_OBJECT:
 case T_CLASS:
 case T_MODULE:
 if (ROBJECT (obj) ->Iv_tbl &&
              St_lookup (ROBJECT (obj) ->Iv_tbl,  Id,  &va=
l) )
 return val;
 break;
 default:
 if (FL_TEST (obj,  FL_EXIVAR) || rb_special_const_p (obj))
 return generic_ivar_get (obj,  Id) ;
 break;
}
 rb_warning ("instance variable %s not initialized", =20
             Rb_id2name (id));

 return Qnil;
}
(variable.c)
Why should Ruby=
 issue a warning and return nil instead of just raising an error? There's p=
robably a good reason for that but I can't see it.
------=_Part_1107_15220505.1301569887791-- ------=_Part_1106_9070286.1301569887779--