views:

95

answers:

1

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.NESTED_CHILD_B" => "Nesting Again",
  "ROOT.CHILD_C" => "K"
}
+5  A: 

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"}
John Douthat
+1 for covering the Arrays too.
Mladen Jablanović