I'm trying to read a text file and then store its individual words in an array. But I can't find a way to split it according to words.
text_file = []
File.open(file, "r") do |f|
f.lines.each do |line|
text_file << line.split.map(&:to_s)
end
end
The above method creates an array of arrays which stores all the words in a single line in an array and so on.
Is there a way in which the array text_file
can hold a single array of all the words?
Yes. Either do:
text_file.push(*line.split.map(&:to_s))
or:
text_file.concat(line.split.map(&:to_s))