It has been long topic now, and very helpful, I must admit I really
love
the Ruby Community, such Community is hard to find other places
I want to thanks everyone very much
It looks like things are a lot clearer for you now. Just a couple
comments on your summary:
The code below would not throw any exception:
puts @myvar
# nil
Ruby already know whatever start with @ would be instance of
something,
if not then it would still be nil object, means false.
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"]
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
2) when they are referenced in an expression, in which case they are
initialized with a reference to the nil object.
3) when they are set via a call to instance_variable_set()
The Accessors only provide you with the set and get properties similar
to other languages, when you declare something like this:
attr_accessor :myvar
You would have an instance of nil object.
This is a bit misleading. There is one and *only* one instance of
NilClass.
So it would be better to say:
You would have a reference to *the* nil object, which is an instance
of NilClass (the *only* instance).
All reference to 'nil' are references to the *same* object:
@a # force @a to exist
@b # force @b to exist
@a.object_id # 4
@b.object_id # 4
nil.object_id # 4
@a.equal?(nil) # true
@b.equal?(nil) # true
nil.equal?(nil) # true
I think the key thing to remember is that 'nil' is not a special
value that
indicates 'no object'. Instead it is a special object that acts as a
sentinel.
There are a number of Ruby conventions that allow nil to act as a
powerful and
useful sentinel:
1) instance variables and global variables default to reference
the nil object.
2) The literal 'nil' always references the same object, the nil
object.
3) There is no way to create additional instances of NilClass.
4) All objects respond to the method: 'nil?'
5) The nil object is the *only* object that responds with 'true'
to 'nil?'.
All other objects respond with 'false'.
6) In a boolean context, 'nil' is considered false.
These properties enable such idioms as:
@foo ||= 'default'
@bar = first_choice || second_choice || third_choice
Ruby's dynamic typing allows 'nil' to be used as a convenient
sentinel value for
many methods. For example 'getc' returns the next byte from an IO
stream as
an instance of Fixnum but if the end of the stream is encountered nil
is returned
instead of a special sentinel instance of Fixnum (e.g. -1 as in the C
programming
language).
Gary Wright