Slurp a file into an array without newlines

lines = IO.read('test.rb').split("\n")

cheers

Simon

···

-----Original Message-----
From: Dick Davies [mailto:rasputnik@gmail.com]
Sent: Thursday, September 29, 2005 11:35 AM
To: ruby-talk ML
Subject: slurp a file into an array without newlines

Coffee....not.....working.......

what's a neater way of doing this?

   lines = File.new('sometextfile').readlines.map { |l| l.chomp }

--
Rasputin :: Jack of All Trades - Master of Nuns

Kroeger Simon (ext) wrote:

···

-----Original Message-----
From: Dick Davies [mailto:rasputnik@gmail.com]
Sent: Thursday, September 29, 2005 11:35 AM
To: ruby-talk ML
Subject: slurp a file into an array without newlines

Coffee....not.....working.......

what's a neater way of doing this?

   lines = File.new('sometextfile').readlines.map { |l| l.chomp }

--
Rasputin :: Jack of All Trades - Master of Nuns

lines = IO.read('test.rb').split("\n")

Problem here is that you have the file twice in mem (as a single string
and as an array of lines). This one is likely more efficient:

lines = File.readlines('sometextfile').each {|l| l.chomp!}

Kind regards

    robert

Lovely, thanks.

···

On 29/09/05, Kroeger Simon (ext) <simon.kroeger.ext@siemens.com> wrote:

> -----Original Message-----
> From: Dick Davies [mailto:rasputnik@gmail.com]
> Sent: Thursday, September 29, 2005 11:35 AM
> To: ruby-talk ML
> Subject: slurp a file into an array without newlines
>
> Coffee....not.....working.......
>
> what's a neater way of doing this?
>
> lines = File.new('sometextfile').readlines.map { |l| l.chomp }
>
> --
> Rasputin :: Jack of All Trades - Master of Nuns

lines = IO.read('test.rb').split("\n")

cheers

Simon

--
Rasputin :: Jack of All Trades - Master of Nuns

Interesting...I didn't know/had forgotten that #each returned a reference to the receiver. Thanks for the tip/reminder :slight_smile:

···

On Sep 29, 2005, at 4:01 AM, Robert Klemme wrote:

lines = File.readlines('sometextfile').each {|l| l.chomp!}

The ri docs don't say - does IO::readlines (like IO::read, and unlike IO#read or IO#readlines) ensure that the file is closed after reading? I assume so, but wanted to be certain.

···

On Sep 29, 2005, at 4:01 AM, Robert Klemme wrote:

lines = File.readlines('sometextfile').each {|l| l.chomp!}

Gavin Kistner wrote:

···

On Sep 29, 2005, at 4:01 AM, Robert Klemme wrote:

lines = File.readlines('sometextfile').each {|l| l.chomp!}

The ri docs don't say - does IO::readlines (like IO::read, and unlike
IO#read or IO#readlines) ensure that the file is closed after
reading? I assume so, but wanted to be certain.

Yes. It has to because no IO object is returned.

    robert