【问题标题】:How do I convert a Ruby hash so that all of its keys are strings如何转换 Ruby 哈希,使其所有键都是字符串
【发布时间】:2015-08-10 01:18:27
【问题描述】:

我有一个 ruby​​ 哈希,看起来像:

{ id: 123, name: "test" }

我想把它转换成:

{ "id" => 123, "name" => "test" }

【问题讨论】:

标签: ruby hash stringify


【解决方案1】:

如果您使用的是 Rails 或 ActiveSupport:

hash = { id: 123, description: "desc" }
hash.stringify #=> { "id" => 123, "name" => "test" }

如果你不是:

hash = { id: 123, name: "test" }
Hash[hash.map { |key, value| [key.to_s, value] }] #=> { "id" => 123, "name" => "test" }

【讨论】:

  • 你有没有问过一个问题,只是自己马上回答?
  • @AlexPan 是的,我做到了。在提交问题时提供答案是 StackOverflow 的一项功能。目标是知识共享。
  • 在较新的 Rails 中,您使用“hash.stringify_keys”api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys
【解决方案2】:

我喜欢each_with_object 在这种情况下:

hash = { id: 123, name: "test" }
hash.each_with_object({}) { |(key, value), h| h[key.to_s] = value }
#=> { "id" => 123, "name" => "test" }

【讨论】:

    【解决方案3】:

    在纯 Ruby(没有 Rails)中,您可以结合使用 Enumerable#mapArray#to_h

    hash = { id: 123, name: "test" }
    hash.map{|key, v| [key.to_s, v] }.to_h
    

    【讨论】:

      【解决方案4】:
      h = { id: 123, name: "test" }
      

      假设你想改变h

      h.keys.each { |k| h[k.to_s] = h.delete(k) }
      h #=> {"id"=>123, "name"=>"test"}  
      

      【讨论】:

        猜你喜欢
        • 2012-01-12
        • 1970-01-01
        • 2015-04-02
        • 2014-09-24
        • 1970-01-01
        • 2010-11-05
        • 1970-01-01
        • 2015-08-24
        • 1970-01-01
        相关资源
        最近更新 更多