Method: IO#each_line
- Defined in:
- io.c
#each_line(sep = $/, chomp: false) {|line| ... } ⇒ self #each_line(limit, chomp: false) {|line| ... } ⇒ self #each_line(sep, limit, chomp: false) {|line| ... } ⇒ self #each_line ⇒ Object
Calls the block with each remaining line read from the stream; returns self. Does nothing if already at end-of-stream; See Line IO.
With no arguments given, reads lines as determined by line separator $/:
f = File.new('t.txt')
f.each_line {|line| p line }
f.each_line {|line| fail 'Cannot happen' }
f.close
Output:
"First line\n"
"Second line\n"
"\n"
"Fourth line\n"
"Fifth line\n"
With only string argument sep given, reads lines as determined by line separator sep; see Line Separator:
f = File.new('t.txt')
f.each_line('li') {|line| p line }
f.close
Output:
"First li"
"ne\nSecond li"
"ne\n\nFourth li"
"ne\nFifth li"
"ne\n"
The two special values for sep are honored:
f = File.new('t.txt')
# Get all into one string.
f.each_line(nil) {|line| p line }
f.close
Output:
"First line\nSecond line\n\nFourth line\nFifth line\n"
f.rewind
# Get paragraphs (up to two line separators).
f.each_line('') {|line| p line }
Output:
"First line\nSecond line\n\n"
"Fourth line\nFifth line\n"
With only integer argument limit given, limits the number of bytes in each line; see Line Limit:
f = File.new('t.txt')
f.each_line(8) {|line| p line }
f.close
Output:
"First li"
"ne\n"
"Second l"
"ine\n"
"\n"
"Fourth l"
"ine\n"
"Fifth li"
"ne\n"
With arguments sep and limit given, combines the two behaviors (see Line Separator and Line Limit).
Optional keyword argument chomp specifies whether line separators are to be omitted:
f = File.new('t.txt')
f.each_line(chomp: true) {|line| p line }
f.close
Output:
"First line"
"Second line"
""
"Fourth line"
"Fifth line"
Returns an Enumerator if no block is given.
4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 |
# File 'io.c', line 4670
static VALUE
rb_io_each_line(int argc, VALUE *argv, VALUE io)
{
VALUE str;
struct getline_arg args;
RETURN_ENUMERATOR(io, argc, argv);
prepare_getline_args(argc, argv, &args, io);
if (args.limit == 0)
rb_raise(rb_eArgError, "invalid limit: 0 for each_line");
while (!NIL_P(str = rb_io_getline_1(args.rs, args.limit, args.chomp, io))) {
rb_yield(str);
}
return io;
}
|