2013-10-09 34 views
0

我是一個總的初學者在紅寶石和一般編碼,我想知道你們是否可以幫助我。我和我的兄弟正在研究一個簡單的ruby代碼,它能夠搜索大量的文本文件以獲取特定的數字。此時我們只能一次搜索一個文本文件。下面的代碼,我們有這麼遠:簡單的數字計數器使用紅寶石

puts "Drag your file to this window and press ENTER" 
file_path = gets.chomp 
puts "\nWhat is your target number?" 
target_number = gets.chomp 

# This will output the number of occurrences of your target number 
file_text = File.read(file_path) 
count = file_text.scan(target_number).count 
puts "\n\nCount: #{count}" 

gets 

我的問題是,我怎樣才能改變這種代碼,以便它在讀取多個文本文件一次,而不是一次一個?

任何幫助,非常感謝!

+4

我想你錯過寫你的問題.. –

回答

1

嘗試使用Dir.glob方法。例如:

files = Dir.glob('*.txt') 
# => ['file1.txt', 'file2.txt'] 

然後你可以通過他們的循環:

count = 0 
for file in files 
    file_text = File.read(file) 
    count += file_text.scan(target_number).count 
end 
puts "\n\nCount: #{count}" 

祝你好運:)