Iterate over each character of a string in Ruby


Jul 02, 2022 | Ruby

At some point, you will want to iterate over each character of a string in Ruby. Here are some of the ways to do it.

In Ruby, defining a string is easy:

name = "Marko"

To split a string into characters, we can use a split command like this:

chars = name.split('')

Here, we used an empty string as separator.

Result of this command is an array of characters, and since it's an array we can iterate over it and print each character out:

chars.each do |char|
  puts char
end

# M
# a
# r
# k
# 0

Next, we can do something crazy, like joining characters back into a string:

new_name = chars.join('')
puts new_name

# Marko

Another way to iterate over a string without storing it into a temporary variable is merging .split and .each like this:

name.split('').each do |char|
  puts char
end

This will split the name with an empty separator, like in our first example and that will return an array, and it will iterate over it like we did in our second example above.

There is yet another way of iterating over characters of a string in Ruby, and that is by using .each_char method like this:

name.each_char do |char|
  puts char
end