将字符串转换为散列符号的最佳方法 [英] Best way to convert strings to symbols in hash
本文介绍了将字符串转换为散列符号的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将(从字符串到字符串)中的所有键转换为Ruby中的符号的(最快/最干净/直接的)方法是什么?
解析YAML时,这将很方便。
my_hash = YAML.load_file('yml')
我希望能够使用:
my_hash [:关键]
而不是:
my_hash ['key']
解决方案
如果您想要单行,
my_hash = my_hash.inject({}){| memo,(k ,v)|备忘录[k.to_sym] = v;备忘录}
会将密码复制到一个新密码中。 $ b
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']
解决方案
If you want a one-liner,
my_hash = my_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
will copy the hash into a new one with the keys symbolized.
这篇关于将字符串转换为散列符号的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文