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

2020-02-17 05:56发布

I am using Ruby on Rails 3.2.2 and I would like to "easily" / "quickly" change hash keys from Symbols to Strings. That is, from {:one => "Value 1", :two => "Value 2", ...} to {"one" => "Value 1", "two" => "Value 2", ...}.

How can I make that by using less code as possible?

9条回答
Emotional °昔
2楼-- · 2020-02-17 06:41

stringify_keys is nice, but only available in Rails. Here's how I would do it in a single line, with zero dependencies:

new_hash = Hash[your_hash.collect{|k,v| [k.to_s, v]}]

This works on Ruby 1.8.7 and up. If you are working with Ruby 2.1, you can do:

new_hash = a.collect{|k,v| [k.to_s, v]}.to_h

Note that this solution is not recursive, nor will it handle "duplicate" keys properly. eg. if you have :key and also "key" as keys in your hash, the last one will take precedence and overwrite the first one.

查看更多
做自己的国王
3楼-- · 2020-02-17 06:51

hash = hash.transform_keys(&:to_s) turns all keys from symbols into strings.

More here: https://ruby-doc.org/core-2.6.3/Hash.html#method-i-transform_keys

This was added in ruby 2.5: https://bugs.ruby-lang.org/issues/13583

查看更多
等我变得足够好
4楼-- · 2020-02-17 06:57

You can transfer the key from symbols to strings explicitly:
hash = hash.map { |k, v| [k.to_s, v] }.to_h

查看更多
登录 后发表回答