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

这在解析YAML时非常方便。

my_hash = YAML.load_file('yml')

我希望能够使用:

my_hash[:key] 

而不是:

my_hash['key']

当前回答

这里有很多答案,但rails函数的一个方法是hash.symbolize_keys

其他回答

对于Ruby中YAML的特定情况,如果键以':'开头,它们将被自动作为符号存储。

require 'yaml'
require 'pp'
yaml_str = "
connections:
  - host: host1.example.com
    port: 10000
  - host: host2.example.com
    port: 20000
"
yaml_sym = "
:connections:
  - :host: host1.example.com
    :port: 10000
  - :host: host2.example.com
    :port: 20000
"
pp yaml_str = YAML.load(yaml_str)
puts yaml_str.keys.first.class
pp yaml_sym = YAML.load(yaml_sym)
puts yaml_sym.keys.first.class

输出:

#  /opt/ruby-1.8.6-p287/bin/ruby ~/test.rb
{"connections"=>
  [{"port"=>10000, "host"=>"host1.example.com"},
   {"port"=>20000, "host"=>"host2.example.com"}]}
String
{:connections=>
  [{:port=>10000, :host=>"host1.example.com"},
   {:port=>20000, :host=>"host2.example.com"}]}
Symbol

这里有很多答案,但rails函数的一个方法是hash.symbolize_keys

我喜欢这一行,当我不使用Rails时,因为这样我就不必在处理它时进行第二个哈希并持有两组数据:

my_hash = { "a" => 1, "b" => "string", "c" => true }

my_hash.keys.each { |key| my_hash[key.to_sym] = my_hash.delete(key) }

my_hash
=> {:a=>1, :b=>"string", :c=>true}

哈希#delete返回已删除键的值

facet的Hash#deep_rekey也是一个不错的选择,特别是:

如果你在项目中发现了其他糖的用途, 如果您更喜欢代码可读性而不是神秘的一行程序。

示例:

require 'facets/hash/deep_rekey'
my_hash = YAML.load_file('yml').deep_rekey

在ruby中,我发现这是最简单、最容易理解的将字符串键转换为符号的方法:

my_hash.keys.each { |key| my_hash[key.to_sym] = my_hash.delete(key)}

对于散列中的每个键,我们调用delete函数将其从散列中删除(delete也返回与被删除的键相关的值),并立即将其设置为符号化的键。