Menu
Coddy logo textTech

Iterating Over Strings

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 3 of 56.

A Ruby string is a sequence of characters, and you can iterate over it directly with each_char:

"ruby".each_char do |c|
  puts c
end
# r
# u
# b
# y

If you also need the index, use each_char.with_index:

"hi".each_char.with_index do |c, i|
  puts "#{i}: #{c}"
end
# 0: h
# 1: i

To get an array of characters in one shot, call chars:

"ruby".chars  # ["r", "u", "b", "y"]
challenge icon

Challenge

Easy

Read a single line of input. Count how many vowels (a, e, i, o, u, case-insensitive) it contains, and print:

Vowels: <count>

For input Hello Ruby, the output is Vowels: 3: e, o, u. (y is not counted.)

Cheat sheet

Iterate over each character in a string with each_char:

"ruby".each_char do |c|
  puts c
end

Use each_char.with_index to also get the index:

"hi".each_char.with_index do |c, i|
  puts "#{i}: #{c}"
end

Convert a string to an array of characters with chars:

"ruby".chars  # ["r", "u", "b", "y"]

Try it yourself

input = gets.chomp
count = 0

# TODO: iterate over each character and count vowels

puts "Vowels: #{count}"
quiz iconTest yourself

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

All lessons in Logic & Flow