Processing standard input with each_line

R

Ronny

To process a file line by line, I use the following idiom:

filename=....
....
File.new(filename).each_line {|line| ..... }

How can I use this approach, when the "file" to be processed, is the
standard input of
my Ruby program?

(In case you know Perl: In Perl, I would set
$filename="-"
because the dash denotes the "special file" standard input in Perl, but
this does not
work in Ruby).

Ronald
 
X

Xavier

To process a file line by line, I use the following idiom:

filename=....
...
File.new(filename).each_line {|line| ..... }

How can I use this approach, when the "file" to be processed, is the
standard input of
my Ruby program?

STDIN.each_line{|l| ....}


Hth
 
R

Robert Klemme

Ronny said:
To process a file line by line, I use the following idiom:

filename=....
...
File.new(filename).each_line {|line| ..... }

You should really use the block form because your code does not close
the file descriptor properly.

File.open(filename) {|io| io.each_line {|line| ... } }

However there's an even simpler approach:

File.foreach(filename) {|line| ... }

Kind regards

robert
 
D

Dave Burt

Ronny said:
To process a file line by line, I use the following idiom:

filename=....
...
File.new(filename).each_line {|line| ..... }

How can I use this approach, when the "file" to be processed, is the
standard input of
my Ruby program?

STDIN aka $stdin is an IO object, just like your File.new(foo). Hence
(using the block form to ensure the file is closed):

File.open(filename) {|f| f.each_line {|line| ... } }
IO.foreach(filename) {|line| ... }

Io_Open(0) {|f| f.each_line {|line| ... } }
STDIN.each_line {|line| ... }

See http://www.ruby-doc.org/core/classes/IO.html

Cheers,
Dave
 
R

Ronny

Dave said:
STDIN aka $stdin is an IO object, just like your File.new(foo). Hence
(using the block form to ensure the file is closed):

File.open(filename) {|f| f.each_line {|line| ... } }
IO.foreach(filename) {|line| ... }

Io_Open(0) {|f| f.each_line {|line| ... } }
STDIN.each_line {|line| ... }

Thank you, that's it!!!!

Ronald
 

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,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top