我開始研究Ruby,並認爲我會構建一些東西;我開始寫一個簡單的配置文件解析器。簡單的原則是,你給它一個格式正確的文件,並且它會分散設置的散列。例如,這是一個配置文件:爲什麼這隻返回第一個設置?
localhost: 4000;
auto: true;
,這就是它給回:
{"localhost" => "4000", "auto" => "true"}
現在,我已經得到了它的工作時,這是用下面的代碼直接輸入:
def spit_direct(input = "", *args)
spat = Hash.new
args.each do |arg|
if input.include? arg
strip = input.match(/#{arg}:\s(\w*);/)
spat[arg] = strip[1]
else
# error message
break
end
end
spat
end
spit_direct("localhost: 4000; auto: true;", "localhost", "auto")
# => {"localhost"=>"4000", "auto"=>"true"}
這工作正如我希望它但我雖然它會更好,如果一個實際的文件可以喂。我想出了下面的代碼但它似乎只返回第一個設置,而不是第二個:
def spit_file(input = "", *args)
spat = Hash.new
args.each do |arg|
File.open(input).each_line do |line|
if line.include? arg
strip = line.match(/#{arg}:\s(\w*);/)
spat[arg] = strip[1]
else
# error message
break
end
end
end
spat
end
如果我給它一個名爲config.cnfg
具有相同內容的上述幾個設置文件,像這樣:
spit_file("(path)/config.cnfg", "localhost", "auto")
它只返回:
# => {"localhost"=>"4000"}
這是爲什麼?昨晚我花了幾個小時,但似乎無法弄清楚什麼問題。
該死的,非常感謝。我也不太確定循環的順序。你可以在這裏加入 – raf
@dnnx嗎? http://chat.stackoverflow.com/rooms/27184/ruby-conceptual –