开发者

One-liner to Convert Nested Hashes into dot-separated Strings in Ruby?

What's the simplest method to convert YAML to dot-separated strings in Ruby?

So this:

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

To this:

{
  "ROOT.CHILD_A" => "Hello",
  "ROOT.CHILD_B.NESTED_CHILD_A" => "Nesting",
  "ROOT.CHILD_B.NES开发者_StackOverflowTED_CHILD_B" => "Nesting Again",
  "ROOT.CHILD_C" => "K"
}


It's not a one-liner, but perhaps it will fit your needs

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

prints

    {"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"}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜