将字符串转换为哈希符号的最佳方法 [英] Best way to convert strings to symbols in hash

查看:42
本文介绍了将字符串转换为哈希符号的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中将哈希中的所有键从字符串转换为符号的(最快/最干净/直接)方法是什么?

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

这在解析 YAML 时会很方便.

This would be handy when parsing YAML.

my_hash = YAML.load_file('yml')

我希望能够使用:

my_hash[:key] 

而不是:

my_hash['key']

推荐答案

In Ruby >= 2.5 (docs) 你可以使用:

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

my_hash.transform_keys(&:to_sym)

使用较旧的 Ruby 版本?这是一个单行,将哈希复制到一个带有符号化键的新哈希中:

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}

通过Rails,您可以使用:

my_hash.symbolize_keys
my_hash.deep_symbolize_keys 

这篇关于将字符串转换为哈希符号的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆