How to import text file and split it up by lines

A

Al Cholic

Hello,

Im attempting to analyze a text file, but having trouble splitting it up
into lines (into an array that indexes each line). Then I would like to
print every line.

Here is what I got:

f = File.open("/Users/john/Desktop/text.txt")

f_lines = f.split("\n")

puts f_lines


And here is the error Im getting:
NoMethodError: private method ‘split’ called for
#<File:/Users/john/Desktop/text.txt>


Dont know why this isnt working. Should be simple enough...

Can someone help please?
 
V

Vasco Andrade e Silva

Al said:
Hello,

Im attempting to analyze a text file, but having trouble splitting it up
into lines (into an array that indexes each line). Then I would like to
print every line.

Here is what I got:

f = File.open("/Users/john/Desktop/text.txt")

f_lines = f.split("\n")

puts f_lines


And here is the error Im getting:
NoMethodError: private method ‘split’ called for
#<File:/Users/john/Desktop/text.txt>


Dont know why this isnt working. Should be simple enough...

Can someone help please?
Hi,

you forgot to 'read' file.

f = File.open("/Users/john/Desktop/text.txt")

f_lines = f.read.split("\n")

puts f_lines

Note: you have also 'each_line' in IO, IOString, String, etc.

Vasco Andrade e Silva
 
C

Chris Shea

Hello,

Im attempting to analyze a text file, but having trouble splitting it up
into lines (into an array that indexes each line). Then I would like to
print every line.

Here is what I got:

f = File.open("/Users/john/Desktop/text.txt")

f_lines = f.split("\n")

puts f_lines

And here is the error Im getting:
NoMethodError: private method 'split' called for
#<File:/Users/john/Desktop/text.txt>

Dont know why this isnt working. Should be simple enough...

Can someone help please?

File.readlines() does everything you need. You don't even need to use
File.new or File.open.

f_lines = File.readlines('/Users/john/Desktop/test.txt')

HTH,
Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top