Forum: Ruby How to import text file and split it up by lines

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C5b20b09d5d24bd554f703ff0595696b?d=identicon&s=25 Al Cholic (desertfox)
on 2007-07-02 03:58
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?
C8e99ac7c04f239eff3c413a972f9ae8?d=identicon&s=25 Vasco Andrade e Silva (vascoas)
on 2007-07-02 04:03
Al Cholic wrote:
> 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
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-07-02 08:17
(Received via mailing list)
On 7/2/07, Vasco Andrade e Silva <vascoas@gmail.com> wrote:
>
> f = File.open("/Users/john/Desktop/text.txt")
>
> f_lines = f.read.split("\n")

There is a convenient shortcut
File.readlines("/User/....")
>
HTH
Robert
C5b20b09d5d24bd554f703ff0595696b?d=identicon&s=25 Al Cholic (desertfox)
on 2007-07-02 09:20
> f_lines = f.read.split("\n")

Thanks man!
This topic is locked and can not be replied to.