user2864194
user2864194

Reputation: 13

Simple Number Counter using Ruby

I'm a total beginner at ruby and coding in general and I was wondering if you guys could help me out. My brother and I are working on a simple ruby code that will be able to search tons of text files for certain numbers. At this moment we only have it able to search one text file at a time. Here's the code we have so far:

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

My question is, how can I change this code so that it reads multiple text files at once rather than one at a time?

Any help is greatly appreciated!

Upvotes: 0

Views: 365

Answers (1)

Delameko
Delameko

Reputation: 2584

Try the Dir.glob method. For example:

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

Then you can loop through them:

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

Good luck :)

Upvotes: 1

Related Questions