Menu
Coddy logo textTech

Iterating Over Strings

Part of the Fundamentals section of Coddy's Ruby journey. Lesson 67 of 88.

Just like arrays, strings in Ruby can be iterated over character by character. The each_char method lets you process every character in a string individually.

Here's how it works:

word = "Ruby"

word.each_char do |char|
  puts char
end

This outputs each character on a separate line: R, u, b, y. The block variable char holds one character at a time as the iterator moves through the string.

If you need both the character and its position, use each_char.with_index:

word = "Hi"

word.each_char.with_index do |char, index|
  puts "#{index}: #{char}"
end

This outputs:

0: H
1: i

Another useful method is chars, which converts a string into an array of its characters. This lets you use all the array methods you've already learned:

letters = "abc".chars
puts letters  # Outputs: a, b, c

These methods are helpful when you need to analyze text, count specific characters, or transform strings character by character.

challenge icon

Challenge

Easy

Read a single line of input containing a string (e.g., hello).

Use each_char.with_index to iterate through the string and print each character along with its position. Each line should follow this format: Position 0: h

After printing all characters with their positions, print the total number of characters in the string on a new line in this format: Total characters: 5

For example, if the input is hello, the output should be:

Position 0: h
Position 1: e
Position 2: l
Position 3: l
Position 4: o
Total characters: 5

If the input is Ruby, the output should be:

Position 0: R
Position 1: u
Position 2: b
Position 3: y
Total characters: 4

If the input is code, the output should be:

Position 0: c
Position 1: o
Position 2: d
Position 3: e
Total characters: 4

If the input is A, the output should be:

Position 0: A
Total characters: 1

Try it yourself

# Read input
str = gets.chomp

# TODO: Write your code below
# Use each_char.with_index to iterate through the string
# Print each character with its position in format: Position X: char


# Print the total number of characters in format: Total characters: X
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Ruby compiler