How to Iterate Over Characters in Ruby: Simple Guide
In Ruby, you can iterate over characters in a string using the
each_char method, which runs a block for each character. This method lets you process or print each character one by one easily.Syntax
The basic syntax to iterate over characters in a string is using each_char method followed by a block. Inside the block, you get each character one at a time.
string.each_char { |char| ... }- runs the block for each charactercharis the variable holding the current character
ruby
string.each_char { |char|
# code using char
}Example
This example shows how to print each character of a string on its own line using each_char.
ruby
word = "hello"
word.each_char { |char| puts char }Output
h
e
l
l
o
Common Pitfalls
A common mistake is trying to use each directly on a string, which does not work because strings are not arrays. Always use each_char to iterate characters.
Also, avoid modifying the string inside the iteration as it can cause unexpected behavior.
ruby
wrong = "test" # wrong.each { |c| puts c } # This will cause an error # Correct way: right = "test" right.each_char { |c| puts c }
Output
t
e
s
t
Quick Reference
Here is a quick summary of methods to iterate over characters in Ruby strings:
| Method | Description |
|---|---|
| each_char | Iterates over each character in the string. |
| chars.each | Converts string to array of characters, then iterates. |
| split("").each | Splits string into characters array, then iterates. |
Key Takeaways
Use the each_char method to iterate over characters in a Ruby string.
Do not use each directly on strings; it causes errors.
You can also convert the string to an array of characters with chars or split before iterating.
Avoid changing the string while iterating over its characters.