3 ms·
Fixnum 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
by macournoyer 15y ago
Fixnum 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 << 1) + 1 # => 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#L225 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#L354-364 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.
- technomancy 15y agoI found it very odd that he would place false before true, but then I realized that's probably just the C mindset leaking through.
- macournoyer 15y agoSince 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#L374 https://github.com/ruby/ruby/blob/trunk/include/ruby/ruby.h#...
- xentronium 15y agoSorry for nitpicking, but you meant 15, not 14. Other than that, it seems you are 100% right.
- macournoyer 15y agoOops! Indeed (7 << 1) + 1 # => 15
- trustfundbaby 15y agoMight 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.
- xentronium 15y agohttp://en.wikipedia.org/wiki/Bit_numbering http://en.wikipedia.org/wiki/Bit_numbering
- apsurd 15y agowow 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)