Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert strings to symbols in hash

Tags:

hashmap

ruby

What's the (fastest/cleanest/straightforward) way to convert all keys in a hash from strings to symbols in Ruby?

This would be handy when parsing YAML.

my_hash = YAML.load_file('yml') 

I'd like to be able to use:

my_hash[:key]  

Rather than:

my_hash['key'] 
like image 594
Bryan M. Avatar asked Apr 28 '09 22:04

Bryan M.


People also ask

How do I convert a string object into a hash object?

read() to read the contents of the file into a variable. In this case IO. read() creates it as a String. Then used eval() to convert the string into a Hash.

What is HashWithIndifferentAccess?

HashWithIndifferentAccess is the Rails magic that paved the way for symbols in hashes. Unlike Hash , this class allows you to access data using either symbols ( :key ) or strings ( "key" ).

What is a Ruby symbol?

Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.


2 Answers

Here's a better method, if you're using Rails:

params.symbolize_keys

The end.

If you're not, just rip off their code (it's also in the link):

myhash.keys.each do |key|   myhash[(key.to_sym rescue key) || key] = myhash.delete(key) end 
like image 61
Sai Avatar answered Oct 15 '22 06:10

Sai


In Ruby >= 2.5 (docs) you can use:

my_hash.transform_keys(&:to_sym) 

Using older Ruby version? Here is a one-liner that will copy the hash into a new one with the keys symbolized:

my_hash = my_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} 

With Rails you can use:

my_hash.symbolize_keys my_hash.deep_symbolize_keys  
like image 39
Sarah Mei Avatar answered Oct 15 '22 06:10

Sarah Mei