使用Ruby的简单数字计数器

时间:2013-10-09 18:39:09

标签: ruby numbers counter

我是红宝石和编码的初学者,我想知道你们是否可以帮助我。我和我的兄弟正在研究一个简单的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

我的问题是,如何更改此代码,以便一次读取多个文本文件而不是一次读取一个文本?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分: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}"
祝你好运:)

相关问题