Re:Ask Matz: why the id of nil is 4?
by xentronium on Thursday February 02, 2012 @02:47PM
(#3544159)
Sorry for nitpicking, but you meant 15, not 14. Other than that, it seems you are 100% right.
Re:Ask Matz: why the id of nil is 4?
by macournoyer on Thursday February 02, 2012 @03:51PM
(#3544396)
Oops! Indeed
(7 << 1) + 1 # => 15
Re:Ask Matz: why the id of nil is 4?
by trustfundbaby on Thursday February 02, 2012 @09:44PM
(#3545486)
Might also want to use 'last' instead of 'first' in this part of your explantion
> tag the first bit w/ 1
I was confused with your explanation until I went and redid the binary on the original, then I got what you meant. sorry if its nitpicky. ignore if you got it.
Re:Ask Matz: why the id of nil is 4?
by xentronium on Friday February 03, 2012 @03:04PM
(#3548681)
Re:Ask Matz: why the id of nil is 4?
by technomancy on Thursday February 02, 2012 @02:45PM
(#3544154)
I found it very odd that he would place false before true, but then I realized that's probably just the C mindset leaking through.
Re:Ask Matz: why the id of nil is 4?
by macournoyer on Thursday February 02, 2012 @03:54PM
(#3544418)
Since in Ruby false and nil are the only "falsish" values and everything else is true, their values has been chosen to make a boolean test as efficient as possible. See: https://github.com/ruby/ruby/blob/trunk/include/ruby/ruby.h#...
wow I didn't know you can multi-line highlight code like that in GitHub. Thanks for the tip!
(click on the second github link and you'll note multiple lines are highlighted. check the url for how it's done)
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:
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.