Ruby Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. Stuck? Open the solution — but give it a real try first. There is usually more than one good Ruby answer.
| # | Exercise | Topics |
|---|---|---|
| 1 | Shopping receipt | loops, format strings |
| 2 | FizzBuzz | conditions, ranges, map |
| 3 | Word frequency | strings, hashes, tally, sort_by |
| 4 | Acronym maker | split, map, join |
| 5 | Grade book | hashes, Enumerable, methods |
| 6 | Run-length encoding | each_char, chunk_while / regex |
| 7 | Custom each | blocks, yield, Enumerable |
| 8 | Stack class | classes, exceptions, visibility |
| 9 | Parse log lines | regex, pattern matching |
| 10 | Inventory value | Data, sum, group_by |
1. Shopping receipt
Print a receipt for the cart below. Each line shows the item name left-aligned in 10 characters and the line total (qty × price) right-aligned in 8 characters with 2 decimals. Finish with a TOTAL line in the same format.
Expected:
Apples 3.60
Bread 2.25
Coffee 15.98
TOTAL 21.83cart = [["Apples", 3, 1.20], ["Bread", 1, 2.25], ["Coffee", 2, 7.99]]
cart.each do |name, qty, price|
# TODO: compute the line total and print it with format
puts name
end
# TODO: print the TOTAL lineApples
Bread
Coffee
Show solution
cart = [["Apples", 3, 1.20], ["Bread", 1, 2.25], ["Coffee", 2, 7.99]]
cart.each do |name, qty, price|
puts format("%-10s %8.2f", name, qty * price)
end
total = cart.sum { |_, qty, price| qty * price }
puts format("%-10s %8.2f", "TOTAL", total)2. FizzBuzz
For the numbers 1 to 15, produce "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and the number itself otherwise. Join everything with spaces.
Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
def fizzbuzz(n)
# TODO: return "Fizz", "Buzz", "FizzBuzz" or n
n
end
puts (1..15).map { |n| fizzbuzz(n) }.join(" ")1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
def fizzbuzz(n)
if (n % 15).zero? then "FizzBuzz"
elsif (n % 3).zero? then "Fizz"
elsif (n % 5).zero? then "Buzz"
else n
end
end
puts (1..15).map { |n| fizzbuzz(n) }.join(" ")3. Word frequency
Write top_words(text, n) that returns the n most frequent words as [word, count] pairs. Ignore case and punctuation. Break ties alphabetically.
Expected: [["the", 3], ["cat", 2], ["a", 1]]
def top_words(text, n)
# TODO: lowercase, extract words, count, sort, take n
[]
end
text = "The cat sat. The cat ran! A dog watched the show."
p top_words(text, 3)[]
Show solution
def top_words(text, n)
text.downcase
.scan(/[a-z']+/)
.tally
.sort_by { |word, count| [-count, word] }
.first(n)
end
text = "The cat sat. The cat ran! A dog watched the show."
p top_words(text, 3)4. Acronym maker
Write acronym(phrase) that builds an acronym from the first letter of every word, in upper case. Words may be separated by spaces or hyphens.
Expected: "PNG", "RTFM", "CMOS"
def acronym(phrase)
# TODO
""
end
p acronym("Portable Network Graphics")
p acronym("read the fine manual")
p acronym("Complementary metal-oxide semiconductor")""
""
""
Show solution
def acronym(phrase)
phrase.split(/[\s-]+/).map { |word| word[0].upcase }.join
end
p acronym("Portable Network Graphics")
p acronym("read the fine manual")
p acronym("Complementary metal-oxide semiconductor")5. Grade book
Given a hash of students and their scores, print each student's average (1 decimal) and letter grade (A ≥ 90, B ≥ 80, C ≥ 70, otherwise F), sorted by average, best first.
Expected:
Noa: 91.0 (A)
Ike: 84.3 (B)
Sol: 65.0 (F)scores = {
"Ike" => [78, 85, 90],
"Noa" => [95, 88, 90],
"Sol" => [60, 72, 63],
}
def letter(avg)
# TODO: return "A", "B", "C" or "F"
"?"
end
scores.each do |name, list|
avg = 0.0 # TODO: compute the average
puts "#{name}: #{avg} (#{letter(avg)})"
endIke: 0.0 (?)
Noa: 0.0 (?)
Sol: 0.0 (?)
Show solution
scores = {
"Ike" => [78, 85, 90],
"Noa" => [95, 88, 90],
"Sol" => [60, 72, 63],
}
def letter(avg)
case avg
when 90.. then "A"
when 80...90 then "B"
when 70...80 then "C"
else "F"
end
end
averages = scores.transform_values { |list| (list.sum.to_f / list.size).round(1) }
averages.sort_by { |_, avg| -avg }.each do |name, avg|
puts "#{name}: #{avg} (#{letter(avg)})"
end6. Run-length encoding
Write encode(str) that compresses runs of the same character: "aaabccdddd" becomes "3ab2c4d" (a count is written only when a run is longer than 1). Then write decode that reverses it.
Expected: "3ab2c4d" and "aaabccdddd"
def encode(str)
# TODO
str
end
def decode(str)
# TODO
str
end
p encode("aaabccdddd")
p decode("3ab2c4d")"aaabccdddd"
"3ab2c4d"
Show solution
def encode(str)
str.chars
.chunk_while { |a, b| a == b }
.map { |run| run.size > 1 ? "#{run.size}#{run.first}" : run.first }
.join
end
def decode(str)
str.gsub(/(\d+)(\D)/) { $2 * $1.to_i }
end
p encode("aaabccdddd")
p decode("3ab2c4d")7. A collection with Enumerable
Complete the Shelf class so that it includes Enumerable and yields each book from each. Then the provided lines should work.
Expected:
["Dune", "Emma", "Ulysses"]
"Ulysses"
730class Shelf
# TODO: include Enumerable
def initialize
@books = {"Emma" => 474, "Dune" => 412, "Ulysses" => 730}
end
# TODO: define each, yielding [title, pages] pairs
end
shelf = Shelf.new
p shelf.respond_to?(:map)false
Show solution
class Shelf
include Enumerable
def initialize
@books = {"Emma" => 474, "Dune" => 412, "Ulysses" => 730}
end
def each(&block)
@books.each(&block)
self
end
end
shelf = Shelf.new
p shelf.map(&:first).sort
p shelf.max_by { |_, pages| pages }.first
p shelf.map(&:last).max8. A safe Stack
Build a Stack class with push (chainable), pop, peek, size and empty?. Popping or peeking an empty stack must raise a custom StackEmptyError. Keep the internal array private.
Expected:
3
3
2
StackEmptyError: stack is emptyclass StackEmptyError < StandardError; end
class Stack
def initialize
@items = []
end
# TODO: push, pop, peek, size, empty?
end
s = Stack.new
p s.respond_to?(:push)false
Show solution
class StackEmptyError < StandardError; end
class Stack
def initialize
@items = []
end
def push(item)
items << item
self
end
def pop
ensure_not_empty!
items.pop
end
def peek
ensure_not_empty!
items.last
end
def size = items.size
def empty? = items.empty?
private
attr_reader :items
def ensure_not_empty!
raise StackEmptyError, "stack is empty" if empty?
end
end
s = Stack.new
s.push(1).push(2).push(3)
p s.size
p s.pop
p s.peek
s.pop
s.pop
begin
s.pop
rescue StackEmptyError => e
puts "#{e.class}: #{e.message}"
end9. Parse log lines
Each log line looks like 2025-03-04 12:01:07 ERROR [db] connection lost. Parse the lines into hashes with :level, :component and :message, then print a count per level and every ERROR message.
Expected:
{"INFO" => 2, "ERROR" => 2, "WARN" => 1}
db: connection lost
api: timeout after 30sLOG = <<~TEXT
2025-03-04 12:00:01 INFO [web] server started
2025-03-04 12:01:07 ERROR [db] connection lost
2025-03-04 12:01:09 WARN [db] retrying
2025-03-04 12:01:12 INFO [db] connected
2025-03-04 12:05:44 ERROR [api] timeout after 30s
TEXT
def parse(line)
# TODO: use a regex with named captures
{}
end
entries = LOG.lines.map { |l| parse(l) }
p entries.first{}
Show solution
LOG = <<~TEXT
2025-03-04 12:00:01 INFO [web] server started
2025-03-04 12:01:07 ERROR [db] connection lost
2025-03-04 12:01:09 WARN [db] retrying
2025-03-04 12:01:12 INFO [db] connected
2025-03-04 12:05:44 ERROR [api] timeout after 30s
TEXT
LINE = /\A\S+ \S+ (?<level>[A-Z]+) \[(?<component>\w+)\] (?<message>.+)\z/
def parse(line)
m = line.chomp.match(LINE)
m && m.named_captures.transform_keys(&:to_sym)
end
entries = LOG.lines.filter_map { |l| parse(l) }
p entries.map { |e| e[:level] }.tally
entries.each do |entry|
case entry
in {level: "ERROR", component:, message:}
puts "#{component}: #{message}"
else
# ignore other levels
end
end10. Inventory value
Model each product with Data.define(:name, :category, :price, :qty). Print the total stock value per category (sorted by value, highest first) and the name of the product with the lowest quantity.
Expected:
tools: 412.5
garden: 120.0
paint: 89.7
Lowest stock: SpadeProduct = Data.define(:name, :category, :price, :qty)
products = [
Product.new("Hammer", "tools", 12.5, 9),
Product.new("Drill", "tools", 75.0, 4),
Product.new("Spade", "garden", 30.0, 2),
Product.new("Hose", "garden", 20.0, 3),
Product.new("Primer", "paint", 8.97, 10),
]
# TODO: value per category and lowest stock
p products.size5
Show solution
Product = Data.define(:name, :category, :price, :qty)
products = [
Product.new("Hammer", "tools", 12.5, 9),
Product.new("Drill", "tools", 75.0, 4),
Product.new("Spade", "garden", 30.0, 2),
Product.new("Hose", "garden", 20.0, 3),
Product.new("Primer", "paint", 8.97, 10),
]
values = products
.group_by(&:category)
.transform_values { |list| list.sum { |p| p.price * p.qty }.round(2) }
values.sort_by { |_, v| -v }.each { |cat, v| puts "#{cat}: #{v}" }
puts "Lowest stock: #{products.min_by(&:qty).name}"Test yourself
Which method counts how often each element occurs in an array?
counttallygroup_byuniq
In exercise 6, what does "aab".chars.chunk_while { |a, b| a == b }.to_a return?
- [["a", "a"], ["b"]]
- ["aa", "b"]
- [["a"], ["a", "b"]]
- {"a" => 2, "b" => 1}
Why sort by [-count, word] in exercise 3?
- To sort by count descending and break ties alphabetically
- To reverse the words
- Because sort_by needs two values
- To remove duplicates