G
gwtmp01
Fixnums and a few other special types (symbols, true/false/nil,
floats?) are assigned as immediate values: Instead of storing a
pointer (or reference) to the value object, the variable stores the
value directly. So in
a=4
'a' does not hold a reference, technically speaking, but rather the
immediate value 4.
This is an implementation issue, and is done for efficiency.
I understand that this is the standard explanation for this sort of
thing but does anyone else feel that it doesn't quite fit? If
Fixnums can have instance variables then doesn't it make more sense
to think of a as containing a reference to the Fixnum object known
as 4?
In what way does a contain the value 4?
$ irb
irb(main):001:0> a = 4
=> 4
irb(main):002:0> a.object_id
=> 9
irb(main):003:0> 4.object_id
=> 9
I'm pretty sure that it is the object ids that are stored in variables
not the associated values. Ruby of course doesn't actually allocate
space
for Fixnums but instead encodes the state of the referenced Fixnum in
the
object_id itself. It can do this because Fixnum state is completely
encoded by its identity (i.e., its object_id).
I know I'm being pedantic (again) but I'd rather think of assignment
as *always* copying references. It is simpler that way. The
fancy bit-twiddling/implementation issues really come into play
when the variable is dereferenced not when assignment occurs. At least
that is the way I've come to think about it. Does anyone else think
about
it that way?
Gary Wright