2010-04-24 2 views

Répondre

13

Ce n'est pas une seule ligne, mais peut-être il répond à vos besoins

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 

impressions

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

+1 pour couvrir les tableaux aussi. –

+0

Belle implémentation récursive. Aimer. –

Questions connexes