On 4/4/07, Gary Wright <gwtmp01 / mac.com> wrote:

> Start a brand new session of IRB and try:
>
> irb> instance_variables
> => []
> irb> @alpha
> => nil
> irb> instance_variables
> => ["@alpha"]
> irb> @beta = 42
> => 42
> irb> instance_variables
> => ["@alpha", "@beta"]
> irb> instance_variable_set("@gamma", 'foo')
> => "foo"
> irb> instance_variables
> => ["@alpha", "@beta", "@gamma"]

Not quite:irb(main):001:0> instance_variables
=> []
irb(main):002:0> @alpha
=> nil
irb(main):003:0> instance_variables
=> []
irb(main):004:0> @beta = 42
=> 42
irb(main):005:0> instance_variables
=> ["@beta"]
irb(main):006:0> defined? @alpha
=> nil
irb(main):007:0> defined? @beta
=> "instance-variable"

> Instance variables come into existence when
>    1) they appear on the left side of an assignment, in which case
> they are
>       initialized to the value on the right hand side of the assignment
Yes
>    2) when they are referenced in an expression, in which case they are
>       initialized with a reference to the nil object.

No, they are not initialized (or even defined) at this point.  They
just evaluate syntactically to nil.  See line 6 above.


>    3) when they are set via a call to instance_variable_set()
>

Yes.


Note that the result of the defined? operator is a syntactic
description of the argument.

 In line 6 above defined? @alpha is not saying that the value of
@alpha is nil, but that since it @alpha isn't defined, there's no
description, and since nil is treated as false in Ruby logical
expressions and anything other than nil and false is treated as true
you can do things like
  p @alpha if defined? @alpha

Here's another subtlety:
irb(main):008:0> defined? nil
=> "nil"

Note that it's not returning the value nil, but the descriptive string "nil".

From the ruby 1.8.5 source, the values which defined? can return are
"assignment", "class variable", "constant", "expression",
"global-variable", "instance-variable", "local-variable",
"local-variable(in-block)", "false", "method", "self", "super",
"true", "yield", and nil

It can also return things like "$1", "$2" etc. and "$$", "$`", "$/",
"$'", and "$+" for regexp match references.  These are only defined
after a regexp match which sets them, until a regexp match which
doesn't.

-- 
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/