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.
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
exampleThis iterator loops over each character in a string
. With each_char
, we introduce an iteration variable. This is a character in the string.
char
. In the example, "c" is the current char
.value = "ruby" # Loop over each character with each_char. value.each_char do |c| # Write char. puts c endr u b y
Each_line
exampleThis iterator loops over all the lines in a string
. If your input string
has newlines, each_line
will return separated strings.
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.