papdel papdel - 27 days ago 11
Ruby Question

How to convert a ruby integer into a symbol

I have a Ruby array like this

q_id = [1,2,3,4,5,...,100]

I want to iterate through the array and convert into a hash like this

:1 => { #some hash} ,
:2 => { #another hash},
:100 => {#yet another hash}

What is the shortest and most elegant way to accomplish this?

[EDIT : the to_s.to_sym while being handy is not how I want it. Apologies for not mentioning it earlier.]

Answer Source

For creating a symbol, either of these work:


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[ *{ |v| [v,{}] }.flatten ]

Or this:

# Every time a previously-absent key is indexed, assign and return a new hash
my_hash ={ |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.