【问题标题】:One-liner to Convert Nested Hashes into dot-separated Strings in Ruby?在 Ruby 中将嵌套哈希转换为点分隔字符串的单线器?
【发布时间】:2011-02-11 18:58:43
【问题描述】:

在 Ruby 中将 YAML 转换为点分隔字符串的最简单方法是什么?

所以这个:

root:
  child_a: Hello
  child_b:
    nested_child_a: Nesting
    nested_child_b: Nesting Again
  child_c: K

到这里:

{
  "ROOT.CHILD_A" => "Hello",
  "ROOT.CHILD_B.NESTED_CHILD_A" => "Nesting",
  "ROOT.CHILD_B.NESTED_CHILD_B" => "Nesting Again",
  "ROOT.CHILD_C" => "K"
}

【问题讨论】:

    标签: ruby parsing yaml


    【解决方案1】:

    它不是单行的,但也许它会满足您的需求

    def to_dotted_hash(source, target = {}, namespace = nil)
      prefix = "#{namespace}." if namespace
      case source
      when Hash
        source.each do |key, value|
          to_dotted_hash(value, target, "#{prefix}#{key}")
        end
      when Array
        source.each_with_index do |value, index|
          to_dotted_hash(value, target, "#{prefix}#{index}")
        end
      else
        target[namespace] = source
      end
      target
    end
    
    require 'pp'
    require 'yaml'
    
    data = YAML.load(DATA)
    pp data
    pp to_dotted_hash(data)
    
    __END__
    root:
      child_a: Hello
      child_b:
        nested_child_a: Nesting
        nested_child_b: Nesting Again
      child_c: K
    

    打印

        {"root"=>
          {"child_a"=>"Hello",
           "child_b"=>{"nested_child_a"=>"Nesting", "nested_child_b"=>"Nesting Again"},
           "child_c"=>"K"}}
        {"root.child_c"=>"K",
         "root.child_b.nested_child_a"=>"Nesting",
         "root.child_b.nested_child_b"=>"Nesting Again",
         "root.child_a"=>"Hello"}
    

    【讨论】:

    • 不错的递归实现。喜欢它。
    猜你喜欢
    • 2014-07-01
    • 2014-01-29
    • 1970-01-01
    • 2010-11-05
    • 2013-11-13
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    相关资源
    最近更新 更多