希望将YAML文件解析为plain key = value字符串。
我有一些初始结构,但我也希望从yaml获得一些键。
test:
line1: "line 1 text"
line2: "line 2 text"
line3: "line 3 text"
options:
item1: "item 1 text"
item2: "item 2 text"
item3: "item 3 text"
红宝石:
File.open("test.yml") do |f|
f.each_line do |line|
line.chomp
if line =~ /:/
line.chop
line.sub!('"', "")
line.sub!(": ", "=")
line.gsub!(/\A"|"\Z/, '')
printline = line.strip
puts "#{printline}"
target.write( "#{printline}")
end
end
end
结果目前看起来像
test:
line1=line 1 text
line2=line 2 text
line3=line 4 text
options:
item1=item 1 text
item2=item 2 text
item3=item 3 text
但是我想在之前添加类别:
test/line1=line 1 text
test/line2=line 2 text
test/line3=line 3 text
options/item1=item 1 text
options/item2=item 2 text
options/item3=item 3 text
为每行添加类别的最佳方法是什么?
答案 0 :(得分:0)
您可以轻松地将YAML转换为哈希:
#test.yml
test:
line1: "line 1 text"
line2: "line 2 text"
line3: "line 3 text"
options:
item1: "item 1 text"
item2: "item 2 text"
item3: "item 3 text"
#ruby
hash = YAML.load File.read('test.yml')
现在,您可以使用哈希,获取密钥,值等来执行任何操作。
hash['options']['item1'] #=> "item 1 text"
hash['test']['line1'] #=> "line 1 text"
答案 1 :(得分:0)
您可以使用YAML#load_file,读取每一行并根据您的需要进行调整:
foo = YAML.load_file('file.yaml').map do |key, value|
value.map { |k, v| "#{key}/#{k}=#{v}" }
end
foo.each { |value| puts value }
# test/line1=line 1 text
# test/line2=line 2 text
# test/line3=line 3 text
# options/item1=item 1 text
# options/item2=item 2 text
# options/item3=item 3 text