Each_char, each_line. Suppose we want to iterate over the characters or lines in a string. We could use a for-loop, with logical branches, but iterators can also be used.
Iterator notes. In Ruby, we often prefer to use iterators to keep code more graceful, reliable and compact. For iterating over strings, we use each_char and each_line.
Each_char example. This iterator loops over each character in a string. With each_char, we introduce an iteration variable. This is a character in the string.
Next On the next iteration, it is assigned to the next char. In the example, "c" is the current char.
Tip As with other "each" iterators, this reduces the possibility of errors when looping in programs.
value = "ruby"# Loop over each character with each_char.
value.each_char do |c|
# Write char.
puts c
endr
u
b
y
Each_line example. This iterator loops over all the lines in a string. If your input string has newlines, each_line will return separated strings.
Important If no newlines occur in the string, only one string will be returned by each_line.
# String literal with 2 newline characters.
data = "Ruby\nPython\nPerl"# Loop over lines with each_line.
data.each_line do |line|
# Write line.
puts line
endRuby
Python
Perl
Looping over strings is a common task in Ruby (and most other programming languages). Iterators can make this task clearer and easier to maintain.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 26, 2023 (edit).