2013-03-29 78 views
0

我開始研究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"} 

這是爲什麼?昨晚我花了幾個小時,但似乎無法弄清楚什麼問題。

回答

3

你做錯了。對於args中的每個arg,再次打開該文件,並且如果此文件的第一行與arg匹配,則哈希將得到更新,然後該文件將被關閉,否則該文件會立即關閉。

倒轉循環嵌套:

def spit_file(input = "", *args) 
    spat = Hash.new 
    File.open(input).each_line do |line| 
    args.each do |arg| 
     if line.include? arg 
     strip = line.match(/#{arg}:\s(\w*);/) 
     spat[arg] = strip[1] 
     end 
    end 
    end 
    spat 
end 


1.9.3p327 :001 > spit_file('cfg.cfg', 'localhost', 'auto') 
=> {"localhost"=>"4000", "auto"=>"true"} 
+0

該死的,非常感謝。我也不太確定循環的順序。你可以在這裏加入 – raf

+0

@dnnx嗎? http://chat.stackoverflow.com/rooms/27184/ruby-conceptual –

1

您的代碼將工作而沒有break語句。它突破了args.each循環而不是each_line循環。第一次沒有確切的參數時,循環會中斷。您應該使用下一條語句。

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 
      next 
     end 
     end 
    end 
    spat 
    end 
相關問題