Ask Matz: why the id of nil is 4?
blog.bigbinary.com
Ask Matz: why the id of nil is 4?
1–10 of 19 posts
Re: Ask Matz: why the id of nil is 4?
#2Re: Ask Matz: why the id of nil is 4?
#3Much less relevant today with Ruby 1.9.x, but still very interesting.
Re: Ask Matz: why the id of nil is 4?
#4Much less relevant today with Ruby 1.9.x, but still very interesting.
The article noted that all integers have odd ids, but not why—the LSB is a http://c2.com/cgi/wiki?TagBit in MRI. I would hope other implementations are permitted to choose different schemes; it would suck if user code began assuming nobody found a use for more than one tag bit.
Re: Ask Matz: why the id of nil is 4?
#5Re: Ask Matz: why the id of nil is 4?
#6Much less relevant today with Ruby 1.9.x, but still very interesting.
Less relevant how? nil.object_id is still 4 in MRI 1.9.2. The article noted that all integers have odd ids, but not why—the LSB is a http://c2.com/cgi/wiki?TagBit in MRI. I would hope other implementations are permitted to choose different schemes; it would suck if user code began assuming nobody found a use for more than one tag bit.
Re: Ask Matz: why the id of nil is 4?
#7For Ruby to know that the value in a pointer is a Fixnum (and not a pointer to an address), it will tag the first bit w/ 1 and shift the integer value by one bit. So storing the value 7 will be done like this:
(7 14
This is why 7.id == 14.You can see where this is implemented right here: https://github.com/ruby/ruby/blob/trunk/include/ruby/ruby.h#...
For true, false and nil they are also stored right in the object pointer using special values defined here: https://github.com/ruby/ruby/blob/trunk/include/ruby/ruby.h#.... You'll notice that those 3 values in binary format all end with 0b...10. First bit to 1 means Fixnum, second bit to 1 means special value: true, false or nil.
Re: Ask Matz: why the id of nil is 4?
#8http://stackoverflow.com/questions/3430280/ruby-how-does-obj...
Re: Ask Matz: why the id of nil is 4?
#9Fixnum values (numbers smaller than native one machine word minus 1 bit) are stored in an object pointer. When you do object.id it returns the address stored in that pointer. For Ruby to know that the value in a pointer is a Fixnum (and not a pointer to an address), it will tag the first bit w/ 1 and shift the integer value by one bit. So storing the value 7 will be done like this: (7 14 This is why 7.id == 14. You c…
Re: Ask Matz: why the id of nil is 4?
#10Fixnum values (numbers smaller than native one machine word minus 1 bit) are stored in an object pointer. When you do object.id it returns the address stored in that pointer. For Ruby to know that the value in a pointer is a Fixnum (and not a pointer to an address), it will tag the first bit w/ 1 and shift the integer value by one bit. So storing the value 7 will be done like this: (7 14 This is why 7.id == 14. You c…