End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
String#each_line
str.each_line(separator=$/, chomp: false) {|substr| block } → str
str.each_line(separator=$/, chomp: false) → an_enumerator
string.c
View on GitHub ↗
static VALUE
rb_str_each_line(int argc, VALUE *argv, VALUE str)
{
RETURN_SIZED_ENUMERATOR(str, argc, argv, 0);
return rb_str_enumerate_lines(argc, argv, str, 0);
}
Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split into paragraphs delimited by multiple successive newlines.
If chomp is true, separator will be removed from the end of each line.
If no block is given, an enumerator is returned instead.
Example
"hello\nworld".each_line {|s| p s} # prints: # "hello\n" # "world" "hello\nworld".each_line('l') {|s| p s} # prints: # "hel" # "l" # "o\nworl" # "d" "hello\n\n\nworld".each_line('') {|s| p s} # prints # "hello\n\n" # "world" "hello\nworld".each_line(chomp: true) {|s| p s} # prints: # "hello" # "world" "hello\nworld".each_line('l', chomp: true) {|s| p s} # prints: # "he" # "" # "o\nwor" # "d"
Ruby version changes
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-
See also
#each_grapheme_cluster
#empty?
#each_codepoint
#encode
also in
4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1