Yossef Mendelssohn wrote:
This is irrelevant from a user's point of view. The logic stays the
same:
b = 1 # or any other object!
a = b # a now points to the same object, 1 in this case
b = 2 # or any other object! a still points to 1 while b points to 2
I only pointed it out because there's no way (that I know of) to show
that a and b point to the same object at one point if a Fixnum is
used. You can use 'hi'.sub!, but there's no 1.succ!
As Robert Klemme pointed out, you can tell whether two variables reference
the same object using object_id
Two references a, and b refer to the same object iff a.object_id ==
b.object_id.
This is true regardless of the class of the object(s) involved in the test.
Object#equal? should also work. Object#== checks object identity by
default, but is often overridden to implement a more 'value based' notion of
equality.
By convention classes are not supposed to override Object#equal?
However, Fixnums can have instance variables, just like any other number.
class Fixnum
attr_accessor :foo
end
5.foo = :bar
4.foo # nil
6.foo # nil
5.foo # :bar
Yes, but I'm not sure what that has to do with determining whether a fixnum
is identical to another object.
By the way, instance variables for immediate objects like fixnums are
implemented differently than instance variables of objects which take up
memory.
For non-immediate objects, the instance data has a pointer to a hash table
which maps the iv name to a value (in Ruby < 1.9) or to shared hash table
which maps the iv name to an index.
For immediate objects, there's a global hash which maps the object_id of the
object to a hash containing that instance's instance variable names and
values.
One thing that immediate objects CAN'T have is a singleton class and
therefore singleton methods.
irb(main):001:0> a = "a String"
=> "a String"
irb(main):002:0> def a.foo;"foo";end
=> nil
irb(main):003:0> a.foo
=> "foo"
irb(main):004:0> a = 1
=> 1
irb(main):005:0> def a.foo;"bah";end
TypeError: can't define singleton method "foo" for Fixnum
from (irb):5
This is because immediate objects don't have a place for the klass pointer
which points to the first module, or module like object searched for
methods, so there's no place to insert a singleton class at the head of the
chain for immediate objects. In the case of immediate objects, the Ruby VM
knows from the bit encoding of the value that it's a FixNum, or nil, or true
..., and starts the search with the particular class.
···
On Tue, Feb 24, 2009 at 4:12 PM, David Masover <ninja@slaphack.com> wrote:
On Feb 23, 3:24 pm, Robert Klemme <shortcut...@googlemail.com> wrote:
--
Rick DeNatale
Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale