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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 26, 2023 (edit).