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
# yIf 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: iTo get an array of characters in one shot, call chars:
"ruby".chars # ["r", "u", "b", "y"]Challenge
EasyRead 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
endUse each_char.with_index to also get the index:
"hi".each_char.with_index do |c, i|
puts "#{i}: #{c}"
endConvert 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}"
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier