Angus
Angus

Reputation: 517

Advice on reading multiple text files into an array with Ruby

I'm currently writing out a program in Ruby, which I'm fairly new at, and it requires multiple text files to be pushed into an array line by line.

I am currently unable to actually test my code since I'm at work and this is for personal use, but I'm seeking advice to see if my code is correct. I knows how to read a file and push it to the array. If possible can someone check it over and advise if I have the correct idea? I'm self taught regarding Ruby and have no-one to check my work.

I understand if this isn't the right place for trying to get this sort of advice and it's deleted/locked. Apologies if so.

contentsArray = []

Dir.glob('filepath').each do |filename|
  next if File.directory?(filename)
  r = File.open("#{path}#{filename}")
  r.each_line { |line| contentsArray.push line}
end

I'm hoping this snippet will take the lines from multiple files in the same directory and stick them in the array so I can later splice what's in there.

Upvotes: 0

Views: 648

Answers (1)

Douglas Lovell
Douglas Lovell

Reputation: 1607

Thank you for the question.

First let's assume that 'filepath' is something like the target pattern you want to glob in Dir.glob('filepath') (I used Dir.glob('src/*.h').each do |filename| in my test).

After that, File.open("#{path}#{filename}") prepends another path to the already complete path you'll have in filename.

And lastly, although this is probably not the problem, the code opens the file and never closes it. The IO object provides a readlines method that takes care of opening and closing the file for you.

Here's some working code that you can adapt:

contentsArray = []

Dir.glob('filepath').each do |filename|
  next if File.directory?(filename)
  lines = IO.readlines(filename)
  contentsArray.concat(lines)
end

puts "#{contentsArray.length} LINES"

Here are references to the Ruby doc's for the IO::readlines and Array::concat methods used:

As an alternative to using the goto (next) the code could conditionally execute on files, like this:

  if File.file?(filename)
    lines = IO.readlines(filename)
    contentsArray.concat(lines)
  end

Upvotes: 2

Related Questions