Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

parsing

ruby

yaml

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"
}
like image 588
Lance Avatar asked Dec 13 '22 22:12

Lance


1 Answers

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"}
like image 185
John Douthat Avatar answered May 01 '23 17:05

John Douthat