method

foreach

v2_4_6 - Show latest stable - Class: IO
foreach(p1, p2 = v2, p3 = v3, p4 = v4, p5 = {})
public

Executes the block for every line in the named I/O port, where lines are separated by sep.

If no block is given, an enumerator is returned instead.

IO.foreach("testfile") {|x| print "GOT ", x }

produces:

GOT This is line one
GOT This is line two
GOT This is line three
GOT And so on...

If the last argument is a hash, it’s the keyword argument to open. See IO.read for detail.

1Note

enumerator and number of lines to read

jkroeze · Mar 19, 2015

== Example
File.foreach(filename) .take(number_of_lines) .map do |line| # ... stuff ... end