2013-07-22 30 views
1

我有一個包含YAML文件:如何將YAML文件中的字段解析爲同一文件中的三個字段?

cat: 
    name: Cat 
    description: catlike reflexes 
dog: 
    name: Dog 
    description: doggy breath 

我要分析它,並打破了描述成key1key2像這樣:

cat: 
    name: Cat 
    description: catlike reflexes 
    info: 
    key1: catlike 
    key2: reflexes 
dog: 
    name: Dog 
    description: doggy breath 
    info: 
    key1: doggy 
    key2: breath 

但是,出於某種原因,我不能這樣做正確。我已經試過到目前爲止是下面的代碼的變化,我覺得我過於複雜:

# to get the original file's data 
some_data = YAML.load(File.open("#{Rails.root}/config/some_data.yml")) 

new_data = some_data.collect do |old_animal| 
    animal = old_animal.second 

    if animal && animal["description"] 
    new_blocks = Hash.new 
    blocks = animal["description"].split(" ") 
    new_blocks["key1"] = blocks.first 
    new_blocks["key2"] = blocks.second 
    animal["info"] = new_blocks 
    end 
    old_animal.second = animal 
    old_animal 
end 

# to write over the original file 
File.write("#{Rails.root}/config/some_data.yml", new_data.to_yaml) 

回答

1

你不說你是否可以在描述多個字,但它是一種所以我會這樣做:

require 'yaml' 

data = YAML.load(<<EOT) 
cat: 
    name: Cat 
    description: catlike reflexes rules 
dog: 
    name: Dog 
    description: doggy breath 
EOT 
data # => {"cat"=>{"name"=>"Cat", "description"=>"catlike reflexes rules"}, "dog"=>{"name"=>"Dog", "description"=>"doggy breath"}} 

此時,來自YAML文件的數據被加載到散列中。遍歷每個哈希鍵/值對:

data.each do |(k, v)| 
    descriptions = v['description'].split 
    keys = descriptions.each_with_object([]) { |o, m| m << "key#{(m.size + 1)}" } 
    hash = keys.each_with_object({}) { |o, m| m[o] = descriptions.shift } 
    data[k]['info'] = hash 
end 

這就是我們回來:

data # => {"cat"=>{"name"=>"Cat", "description"=>"catlike reflexes rules", "info"=>{"key1"=>"catlike", "key2"=>"reflexes", "key3"=>"rules"}}, "dog"=>{"name"=>"Dog", "description"=>"doggy breath", "info"=>{"key1"=>"doggy", "key2"=>"breath"}}} 

它什麼樣子,如果它是輸出:

puts data.to_yaml 
# >> --- 
# >> cat: 
# >> name: Cat 
# >> description: catlike reflexes rules 
# >> info: 
# >>  key1: catlike 
# >>  key2: reflexes 
# >>  key3: rules 
# >> dog: 
# >> name: Dog 
# >> description: doggy breath 
# >> info: 
# >>  key1: doggy 
# >>  key2: breath 

each_with_objectinject類似,但使用起來更簡潔一些,因爲它不要求我們返回正在積累的對象。

+0

看起來不錯,我遇到的一個問題實際上超出了我所問的範圍,但我總是有4個鍵,裏面的2個需要合併。我不知道如何編輯你的代碼,使它如此 –

+0

我有點想通了(看起來很拙劣,因爲我硬編碼的鍵等),但它適用於一次性使用! –

+1

當您提出問題時,準確地陳述問題並顯示預期數據非常重要。如果您預先指定了REAL需求,那麼答案會有所不同,您可能不需要「破解」任何東西。修改原來的問題,使其準確無誤,我將相應地調整答案。 –

相關問題