From: Vicente Bosch Campos Date: 2011-03-31T23:04:43+09:00 Subject: Re: Dereferencing instance variables vs local variables/methods Regarding this issue I have come to the same conclusion as Gunther. On one side of the balance we get some flexibility and we are allowed to not have to initialize all class variables in the initialize method on the other we are exposing ourselves that if at any time this changes we might have a lot of non working software on our hands. ( which is highly unlikely). Still I prefer it like it is, it is a sort of convention over configuration. ( You wan't nil ? Don't do anything its already done for you) On Mar 31, 2011, at 1:44 PM, Gunther Diemant wrote: > Consider something like this > > class Foo > def set_bar(value) > @bar = value > end > > def some_method > @bar ? "@bar is not nil or false" : "@bar is not set" > end > end > > If ruby raises an error when you call some_method before set_bar, you are > forced to write a initialize method with @bar = nil in it. > > 2011/3/31 Josep M. Bach > >> 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. >> >>