How to convert a ruby integer into a symbol

For creating a symbol, either of these work:

42.to_s.to_sym
:"#{42}"

The #inspect representation of these shows :"42" only because :42 is not a valid Symbol literal. Rest assured that the double-quotes are not part of the symbol itself.

To create a hash, there is no reason to convert the keys to symbols, however. You should simply do this:

q_id = (1..100).to_a
my_hash_indexed_by_value = {}
q_id.each{ |val| my_hash_indexed_by_value[val] = {} }

Or this:

my_hash = Hash[ *q_id.map{ |v| [v,{}] }.flatten ]

Or this:

# Every time a previously-absent key is indexed, assign and return a new hash
my_hash = Hash.new{ |h,val| h[val] = {} }

With all of these you can then index your hash directly with an integer and get a unique hash back, e.g.

my_hash[42][:foo] = "bar"

Unlike JavaScript, where every key to an object must be a string, Hashes in Ruby accept any object as the key.


Actually "symbol numbers" aren't a thing in Ruby (try to call the to_sym method on a number). The benefit of using symbols in a hash is about performance, since they always have the same object_id (try to call object_id on strings, booleans, numbers, and symbols).

Numbers are immediate value and, like Symbol objects, they always have the same object_id.

Anyway, using the new hash syntax implies using symbols as keys, but you can always use the old good "hash rocket" syntax

awesome_hash = { 1 => "hello", 2 => "my friend" }

Read about immediate values here:

https://books.google.de/books?id=jcUbTcr5XWwC&pg=PA73&lpg=PA73&dq=immediate+values+singleton+method&source=bl&ots=fIFlAe8xjy&sig=j7WgTA1Cft0WrHwq40YdTA50wk0&hl=en&sa=X&ei=0kHSUKCVB-bW0gHRxoHQAg&redir_esc=y#v=onepage&q&f=false


To translate an integer into a symbol, use to_s.to_sym .. e.g.,:

1.to_s.to_sym

Note that a symbol is more related to a string than an integer. It may not be as useful for things like sorting anymore.

Tags:

Ruby