0

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh thank you. I wasn't too far off, not bad for someone taking a complete guess. I'll give it a go in a few hours and see what happens. Thanks for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.