Ruby: How to store each line from many .txt files into one variable

Viewed 80

I have to store several lines from .txt files which are located in different directories into variable but I don't know how.

This is my code for printing every line from those .txt files and it works fine, but I don't know how to store them into one variable.

Dir.chdir "/path/to/dir"
Dir.glob("**/*.{mo,txt}").each do |filename|
  File.open(filename, "r") do |f|
    f.each_line do |line|
            puts line
        end
    end
end

I'm beginner in ruby so please help!!

1 Answers

An array would be perfect for this

array = []
Dir.chdir "/path/to/dir"
Dir.glob("**/*.{mo,txt}").each do |filename|

  File.open(filename, "r") do |f|
    f.each_line do |line|
      array << line.gsub(/[\r\n]+/, ' ')
    end
  end
end

If you want an alternative solution:

Dir.glob("**/*.{mo,txt}").each do |filename|
  File.foreach(filename).map { |line| array << line.gsub(/[\r\n]+/, ' ') }
end

the regex being subbed on line is to remove any unwanted newline characters. So a file consisting of

1
2
3
4
5

without the regex, would fill your array with:

["1\n", "2\n", "3\n", "4\n", "5\n"]

with the regex, would fill your array with:

["1", "2", "3", "4", "5"]
        
Related