String#each_line

str.each_line(separator=$/) { |line| block } -> str
Returns: String or Enumerator · Updated March 13, 2026 · String Methods
strings iteration lines parsing

The each_line method splits a string or reads from an IO object and iterates over each line. It’s the foundational method for line-by-line text processing.

With Strings

# Basic iteration
text = "line1\nline2\nline3"
text.each_line { |l| puts l }

# Output:
# line1
# line2
# line3

With Custom Separators

# Split by comma
csv = "a,b,c,d"
csv.each_line(",") { |s| puts s }
# a
# b
# c
# d

# Split by paragraph (empty string)
text.each_line("") { |p| puts p }

Practical Examples

File Processing

# Each line from string
content = File.read("data.txt")
content.each_line do |line|
  line.chomp!
  process(line)
end

Line Number Tracking

text = "one\ntwo\nthree"
text.each_line.with_index do |line, i|
  puts "#{i + 1}: #{line}"
end
# 1: one
# 2: two
# 3: three

Filtering Lines

text = "error: file not found\ninfo: starting\nerror: timeout"

errors = []
text.each_line do |line|
  errors << line if line.start_with?("error:")
end

With Chomp

# Common pattern
text.each_line.chomp.each { |line| ... }

Return Values

# Returns string if block given
result = "a\nb\nc".each_line { |l| l.upcase }
# => "a\nb\nc"

# Returns enumerator if no block
enum = "a\nb\nc".each_line
enum.first  # => "a"

Alternative Separators

# Custom separators
"word1|word2|word3".each_line("|") { |w| puts w }
# word1
# word2
# word3

Memory Efficiency

# For large files, use File.each_line (streams)
File.each_line("huge.txt") do |line|
  process(line)  # One line at a time
end  # Doesn't load entire file

Comparison

# each_line = each (default separator)
"a\nb".each_line == "a\nb".each

This method is essential for text processing, log analysis, and any task involving line-oriented data.

See Also