2012-08-06 62 views
0

我試圖逐行檢查文件,如果該行包含散列鍵,我想打印該值。例如:檢查散列鍵是否出現在一行中

Months = { "January" => 1, 
      "February" => 2, 
      "March" => 3 
     } 

,如果我有一個包含文件:

February 
January 
March 

我所要的輸出是:

2 
1 
3 

誰能給我一些建議快?

回答

1
months = { "January" => 1, "February" => 2, "March" => 3 } 

File.open('yourfile.txt').each_line do |line| 
    result = months[line.strip] 
    puts result if result 
end 
+0

嗯哼。謝謝你。我忘記提及的是,我的線上有多個字符。有沒有一個快速解決我的代碼與上述代碼來解決這個問題?例如,如果行包含 「 月份是2月 的月份是一月 的月份是3 」每個 在不同線路上 – 2012-08-06 20:27:03

+2

@JaronBradley,評論沒有意義。 「我的路線上有多個角色」是什麼意思?我們需要在您的問題中看到示例,顯示數據可能出現的各種方式。 – 2012-08-06 22:33:41

+1

@JaronBradley,當然不確定你的數據文件,但這裏有一些可能的修復方法http://pastie.org/4403285 – 2012-08-07 02:09:24

2

假設下面的數據結構:

data = 'Months = { "January" => 1, 
    "February" => 2, 
    "March" => 3 
}' 

這將掃描通過它找到月份名稱相關的數字:

months_to_find = %w[January February March] 
months_re = Regexp.new(
    '(%s) .+ => \s+ (\d+)' % months_to_find.join('|'), 
    Regexp::IGNORECASE | Regexp::EXTENDED 
) 
Hash[*data.scan(months_re).flatten]['January'] # => 1 

神奇的出現在這裏:

months_re = Regexp.new(
    '(%s) .+ => \s+ (\d+)' % months_to_find.join('|'), 
    Regexp::IGNORECASE | Regexp::EXTENDED 
) 

哪個crea TES此正則表達式:

/(January|February|March) .+ => \s+ (\d+)/ix 

添加額外個月months_to_find

如果數據更改爲這將繼續工作:

data = 'Months = { "The month is January" => 1, 
    "The month is February" => 2, 
    "The month is March" => 3 
}' 
相關問題