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条回答
萌系小妹纸
2楼-- · 2020-02-17 06:30

simply call stringify_keys (or stringify_keys!)

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

查看更多
不美不萌又怎样
3楼-- · 2020-02-17 06:30

stringify_keys from rails

http://api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys

hash = { name: 'Rob', age: '28' }
hash.stringify_keys
# => { "name" => "Rob", "age" => "28" }
查看更多
乱世女痞
4楼-- · 2020-02-17 06:37
 new_hash = Hash.new
 your_hash.each{ |k,v| new_hash[k.to_s] = v }

new_hash will be same as your_hash but with string keys

查看更多
女痞
5楼-- · 2020-02-17 06:37

I came here to see if there was something better than:

JSON.parse(hash.to_json)

But I think I'll stick with what I have.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2020-02-17 06:38

Use stringify_keys/stringify_keys! methods of the Hash class.

You can also use some_hash.with_indifferent_access to return a Hash instance where your key can be specified as symbols or as strings with no difference.

查看更多
神经病院院长
7楼-- · 2020-02-17 06:40

there is a nice library that does the trick, the library is "facets/hash/rekey" and the method is rekey!. Se my example below of how to use it. It is just a copy past of

> require 'facets/hash/rekey'
 => true
> a = {:one => "Value 1", :two => "Value 2"}
 => {:one=>"Value 1", :two=>"Value 2"} 
> a.rekey!(&:to_s)
 => {"one"=>"Value 1", "two"=>"Value 2"} 
> a
 => {"one"=>"Value 1", "two"=>"Value 2"}
查看更多
登录 后发表回答