Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Ruby symbols to integers

Tags:

ruby

I find it surprising that Ruby symbols can be typecasted to integers without errors. So :a.to_i is legal. I was wondering what is the significance of this integer, is it a unique value specific to that symbol?

like image 536
lorefnon Avatar asked Mar 23 '12 05:03

lorefnon


2 Answers

You shouldn't do this, as Symbol#to_i was removed in Ruby 1.9 and is thus not compatible going forward. Regardless, the docs say this about it:

Returns an integer that is unique for each symbol within a particular execution of a program.

It is roughly equivalent to calling object_id on the symbol, as they both end up calling the C function SYM2ID().

like image 171
Andrew Marshall Avatar answered Oct 21 '22 11:10

Andrew Marshall


In 1.8.x symbols were immediate objects. Their implementation was fast, and, most of the time, small. But with that came a security concern regarding the lack of garbage collection.

The #to_i and #to_int methods returned a unique integer and were related to the internal implementation.

Symbols-as-immediates and the implicit and explicit integer conversions have all been removed in 1.9.x. You can of course get the object_id. It's interesting that in 1.8.x to_i and object_id did not return the same number.

like image 21
DigitalRoss Avatar answered Oct 21 '22 09:10

DigitalRoss