2013-10-09 35 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}" 

祝你好运:)