2010-04-24 35 views
2

在Ruby中將YAML轉換爲點分隔字符串的最簡單方法是什麼?在Ruby中將嵌套哈希轉換爲點分隔字符串的單向函數?

所以這樣的:

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

回答

13

這不是一個班輪,但也許它會滿足您的需求

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

+1也用於覆蓋陣列。 – 2010-04-24 15:12:13

+0

漂亮的遞歸實現。愛它。 – 2013-05-02 07:00:42

相關問題