String#each_char
str.each_char { |char| block } -> str Returns:
string · Updated March 13, 2026 · String Methods strings iteration characters lines enumerable
each_char and each_line are String methods that iterate over the characters or lines of a string, respectively. They are useful for processing text data character-by-character or line-by-line when you need fine-grained control over text parsing.
Syntax
str.each_char { |char| block } -> str
str.each_line(separator=$/) { |line| block } -> str
Parameters
each_char
No parameters. Yields each character in the string as a single-character string.
each_line
| Parameter | Type | Default | Description |
|---|---|---|---|
separator | String | $/ (newline) | The line separator. Can be any string. Pass an empty string for paragraph mode. |
Examples
each_char basic usage
"hello".each_char { |c| print c, " " }
# => h e l l o
each_char building a character array
chars = []
"ruby".each_char { |c| chars << c }
chars
# => ["r", "u", "b", "y"]
each_line basic usage
text = "line one\nline two\nline three"
text.each_line { |l| puts l }
# line one
# line two
# line three
each_line with custom separator
"a,b,c".each_line(",") { |part| puts part }
# a
# b
# c
each_line with empty separator for paragraphs
text = "para one\n\npara two\n\npara three"
text.each_line("") { |p| puts p; puts "---" }
Common Patterns
Character frequency counting
frequency = Hash.new(0)
"hello world".each_char { |c| frequency[c] += 1 }
frequency
# => {"h"=>1, "e"=>1, "l"=>3, "o"=>2, " "=>1, "w"=>1, "r"=>1, "d"=>1}
Processing file contents line by line
File.read("data.txt").each_line.with_index do |line, i|
puts "#{i + 1}: #{line}"
end
Using Enumerator for lazy iteration
enum = "hello".each_char
enum.next
# => "h"
enum.next
# => "e"
enum.peek
# => "l"
Transforming each character
"hello".each_char.map { |c| c.upcase }
# => ["H", "E", "L", "L", "O"]
Performance Note
For simple character iteration, each_char is more efficient than splitting into an array first (string.chars.each). The method returns an Enumerator when called without a block, allowing method chaining with other Enumerable methods.
When processing large files, consider reading line-by-line with File.foreach instead of loading the entire file into memory first.