Reputation: 3120
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?
Upvotes: 0
Views: 1617
Reputation: 8403
The following reads the contents of file
, splits lines and words delimited by spaces, and then makes a constant called WORDS
by freezing the result.
WORDS = File.read(file).split(/[ \n]/).freeze
If you also want to use tabs as well as spaces and newlines as delimiters use the following:
WORDS = File.read(file).split(/[ \n\t]/).freeze
Upvotes: 0
Reputation: 9497
Modifying your code, this will do the trick:
text_file = []
File.open('document.rb', "r") do |f|
f.each_line do |line|
arr = line.split(' ')
arr.each do |word|
text_file << word
end
end
end
Upvotes: 0
Reputation: 211590
If you want all of the words, uniquely, sorted:
text_file = [ ]
File.open(file, "r") do |f|
f.each_line do |line|
text_file += line.split
end
end
text_file.uniq!
text_file.sort!
This is not the most optimal implementation, but it should work. To adapt this to more real-world situations you probably need to use String#scan
to pull out more specific words instead of getting tripped up on things like punctuation or hyphens.
Upvotes: 1
Reputation: 168101
Yes. Either do:
text_file.push(*line.split.map(&:to_s))
or:
text_file.concat(line.split.map(&:to_s))
Upvotes: 2