Best Way to Convert Strings to Symbols in Hash

Best way to convert strings to symbols in hash

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

Best way to convert strings to symbols in hash

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

How to change hash keys from `Symbol`s to `String`s?

simply call stringify_keys (or stringify_keys!)

http://apidock.com/rails/Hash/stringify_keys

Convert string to symbol/keyword

No, there isn't.

It's important to note that these two lines do exactly the same:

{ foo: 'bar' }    #=> {:foo=>"bar"}
{ :foo => 'bar' } #=> {:foo=>"bar"}

This is because the first form is only Syntactic sugar for creating a Hash using a Symbol as the Key. (and not "the new way of defining keyword in ruby")

If you want to use other types as the key, you still have to use the "hashrocket" (=>):

{ 'key' => 'val' } #=> {"key"=>"val"}
{ 0 => 'val' } #=> {0=>"val"}

Edit:

As @sawa noted in the comments, the question is about passing keyword arguments, not Hashes. Which is technically correct, but boils down to exactly the same (as long as it's Hashes with Symbols as keys:

def foo(bar: 'baz')
puts bar
end

h = {
:bar => 'Ello!'
}

foo(h)
# >> Ello!

Unwanted symbol to string conversion of hash key

It may end up as a HashWithIndifferentAccess if Rails somehow gets ahold of it, and that uses string keys internally. You might want to verify the class is the same:

assert_equal Hash, assigns(:my_hash).class

Parameters are always processed as the indifferent access kind of hash so you can retrieve using either string or symbol. If you're assigning this to your params hash on the get or post call, or you might be getting converted.

Another thing you can do is freeze it and see if anyone attempts to modify it because that should throw an exception:

@my_hash = { :my_key => :my_value }.freeze


Related Topics



Leave a reply



Submit