--00504502d319f75192049fc5d029
Content-Type: text/plain; charset=ISO-8859-1

Consider something like this

class Foo
  def set_bar(value)
    @bar  alue
  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  il in it.

2011/3/31 Josep M. Bach <josep.m.bach / gmail.com>

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

--00504502d319f75192049fc5d029--