Thuta Learning
Ruby
ExercisesProgrammingBeginner

Practice Exercises 2

RubyLesson 3450 min

What you'll walk away with

  • Build small classes with initialize, readers and a custom ==/hash so equal books are recognised
  • Return Arrays (never nil) from search methods and use Enumerable through each
  • Count words with Hash.new(0) and explain why Hash.new([]) is a trap
  • Write methods that take a block with yield, and use block_given? or an Enumerator when none is given
  • Break ties on purpose (alphabetically) instead of by accident

Explain it simply

Explain it simply

This lesson combines three ideas from the later chapters: classes with state, blocks, and hashes used as counters. Each task is small, but together they look like the building blocks of real programs: a model class, a collection that searches itself, a counter, and a method that lets the caller decide what to do with each item.

Use the same routine as in Practice Exercises 1: write your own solution first, predict the output, run it, and only then compare. This time pay special attention to what each method returns, because returning the right kind of value (an Array, a Hash, an Enumerator) is half of the exercise.

Problem → Why → Solution

The problem: a draft that works for the sample and fails silently

A first draft of the library tasks usually works for exactly the sample from the task statement and then fails in small, silent ways. find_by_author compares book == name instead of book.author == name, so it returns an empty array and no error appears. Two Books with the same title are happily added twice, because two objects with the same data are different objects unless you define ==. A word_frequency written with Hash.new([]) seems to work for the first word and then puts every word into one shared array. And yield_even_numbers raises LocalJumpError when someone calls it without a block.

None of these are syntax errors. They are all cases where Ruby does something reasonable that is not what you meant, and the only defence is to run the odd inputs.

first_draft.rb
class Book
  attr_reader :title, :author

  def initialize(title, author)
    @title = title
    @author = author
  end
end

library = [Book.new("Ruby Basics", "Matz")]
p library.select { |book| book == "Matz" }    # [] - a Book never equals a String
p Book.new("Ruby Basics", "Matz") == Book.new("Ruby Basics", "Matz")   # false

counts = Hash.new([])
"ruby is fun".split.each { |word| counts[word] << word }
p counts            # {} - every << changed the one shared default array
p counts["zzz"]     # ["ruby", "is", "fun"]

def yield_even_numbers(numbers)
  numbers.each { |n| yield n if n.even? }
end

yield_even_numbers([1, 2])   # LocalJumpError: no block given (yield)

Why doesn't Ruby report any of this?

Ruby is dynamic and forgiving: comparing unrelated objects with == just returns false, a missing hash key returns the default, and a Hash default that is an Array is the very same Array every time. Nothing is wrong from Ruby's point of view, so nothing is reported. The cure is to decide the contract of each method (what it accepts and what it always returns) and to test the awkward cases deliberately.

Core concept: classes, blocks and counters with a clear contract

These four tasks share one habit: before you write the body, decide what the method promises. The promise has three parts: the kind of value it always returns, what it does for empty or nil input, and who decides how each item is handled.

1. Give the class a small, honest interface

Book needs a title and an author, so initialize requires both and rejects blank ones. attr_reader exposes them without setters, which makes books safe to share between a library and a report. If two books should count as the same book when title and author match, define == (together with eql? and hash) on those fields; otherwise every object is unique, even with identical data.

2. Let the collection use Enumerable

Library keeps @books private, defines each and includes Enumerable. Then find_by_author is a select over self, most_prolific_author is a tally, and no method needs to touch the array directly. Search methods return an Array even when nothing matches, so callers can chain map or size without a nil check.

3. Pick a counter whose default is safe

Hash.new(0) gives every missing key the value 0, so counts[word] += 1 works from the first sighting. The block form Hash.new { |hash, key| hash[key] = [] } is the safe way to build a list per key, because it creates a fresh array every time. Hash.new([]) hands out one shared array. tally does the counting in one call and returns a plain Hash with no default.

4. Decide the rule for ties

When two authors have the same number of books, a method like max_by quietly returns the first one it met, which depends on insertion order. Make the rule explicit: sort by [-count, name] so the highest count wins and ties go to the alphabetically first name. Then the answer is the same no matter how the data arrived.

5. Let the caller's block do the work

yield hands each item to the block the caller wrote. Without a block, yield raises LocalJumpError. Check block_given? and either raise a clear error or, more helpfully, return an Enumerator with to_enum so callers can chain .to_a or .map. Skip anything that is not an Integer instead of crashing halfway through.

MethodAlways returnsEmpty or nil input
find_by_author(name)An Array[] for nil, blank or unknown names
most_prolific_authorA String or nilnil for an empty library
word_frequency(text)A Hash of String => Integer{} for "" or nil
yield_even_numbers(list)An Enumerator without a block, otherwise the count it yieldedYields nothing and returns 0
Mental model: a promise, then the body
  1. Decide what the method always returns
  2. Decide what empty and nil input do
  3. Decide how ties and duplicates behave
  4. Write the body, then call the odd inputs

A method whose return type changes with the input (sometimes nil, sometimes an Array) forces every caller to check. Fix the type first and the callers stay simple.

General pattern

ruby
def each_match(items, wanted)
  return to_enum(:each_match, items, wanted) unless block_given?

  items.each do |item|
    yield item if item == wanted
  end
end

counts = Hash.new(0)
words.each { |word| counts[word] += 1 }
each_match(words, "ruby") { |word| puts word }

The first part yields each item when a block is given and returns an Enumerator otherwise. The second part uses a Hash.new(0) counter, and the last line shows a call that passes a block.

Reference solutions for the four tasks

Compare these with your own solution only after you have tried. They go beyond the sample calls in the tasks: Book equality and the library refusing a duplicate, find_by_author with an unknown name and with nil, a tie in most_prolific_author, word_frequency with punctuation, mixed case and Myanmar words, and yield_even_numbers with nil and Float entries or without a block. Hash output uses Ruby 4.0.9's format; older versions print {"ruby"=>2}.

oop_blocks_solutions.rb
# Task 1: a Book is read-only after creation. Two books with the same title and
# author (ignoring case) count as the same book.
class Book
  attr_reader :title, :author

  def initialize(title, author)
    raise ArgumentError, "title can't be blank" if title.to_s.strip.empty?
    raise ArgumentError, "author can't be blank" if author.to_s.strip.empty?

    @title = title.strip
    @author = author.strip
  end

  def ==(other)
    other.is_a?(Book) && identity == other.identity
  end
  alias eql? ==

  def hash = identity.hash

  def to_s = "#{title} by #{author}"

  protected

  def identity = [title.downcase, author.downcase]
end

# Task 2: a Library keeps Books and can search them.
class Library
  include Enumerable

  def initialize
    @books = []
  end

  def add_book(book)
    raise ArgumentError, "already in the library: #{book}" if @books.include?(book)

    @books << book
    self
  end

  def each(&block)
    return enum_for(:each) unless block

    @books.each(&block)
    self
  end

  # Always returns an Array, never nil. Unknown, blank or nil names give [].
  def find_by_author(name)
    wanted = name.to_s.strip.downcase
    return [] if wanted.empty?

    select { |book| book.author.downcase == wanted }
  end

  # Ties go to the author who comes first alphabetically; nil for an empty library.
  def most_prolific_author
    counts = map(&:author).tally
    return nil if counts.empty?

    counts.min_by { |author, count| [-count, author] }.first
  end
end

# Task 3: count each word. Hash.new(0) makes a missing word start at 0.
def word_frequency(text)
  counts = Hash.new(0)
  text.to_s.downcase.scan(/[\p{L}\p{M}\p{N}']+/) { |word| counts[word] += 1 }
  counts
end

# Task 4: yield only the even Integers and return how many were yielded.
# Without a block it returns an Enumerator instead of raising LocalJumpError.
def yield_even_numbers(numbers)
  return to_enum(:yield_even_numbers, numbers) unless block_given?

  count = 0
  numbers.each do |n|
    next unless n.is_a?(Integer) && n.even?

    yield n
    count += 1
  end
  count
end

library = Library.new
library.add_book(Book.new("Ruby Basics", "Matz"))
       .add_book(Book.new("Programming Ruby", "Dave Thomas"))
       .add_book(Book.new("Ruby Under a Microscope", "Pat Shaughnessy"))
       .add_book(Book.new("Eloquent Ruby", "Russ Olsen"))
       .add_book(Book.new("More Ruby", "Matz"))

puts library.find_by_author("matz").map(&:to_s)
p library.find_by_author("Nobody")
p library.find_by_author(nil)
puts "Most prolific: #{library.most_prolific_author}"
p Library.new.most_prolific_author

begin
  library.add_book(Book.new("RUBY BASICS", " matz "))
rescue ArgumentError => e
  puts "Rejected: #{e.message}"
end

freq = word_frequency("Ruby is fun and ruby is easy!")
puts freq.map { |word, count| "#{word}=#{count}" }.join(" ")
puts freq["missing"], freq.key?("missing")
p word_frequency("")
p word_frequency("မြန်မာစာ ရေးတယ် မြန်မာစာ")

yielded = yield_even_numbers([1, 2, 3, 4, 5, 6]) { |n| puts n }
puts "yielded #{yielded} numbers"
p yield_even_numbers([1, 2, 3, 4, 5, 6]).to_a
p yield_even_numbers([-4, 0, 7, nil, 2.0, "8"]).map { |n| n * 10 }
p yield_even_numbers([]).to_a

Code breakdown

  1. Equality for hashes and uniqalias eql? ==

    Hash keys, uniq and Set use eql? and hash, not ==. So when you define ==, alias eql? to it and give equal books the same hash with def hash = identity.hash. Only when all three agree is "RUBY BASICS" by " matz " recognised as the existing "Ruby Basics" by "Matz".

  2. A protected comparison keydef identity = [title.downcase, author.downcase]

    identity is the case-insensitive key made from title and author. protected means other Book objects may call it but outsiders may not, which is what lets other.identity work inside ==.

  3. Compare the attribute, not the objectselect { |book| book.author.downcase == wanted }

    Writing book == wanted would compare a Book with a String, never equal, giving an empty array. This line compares book.author instead. wanted is already stripped and downcased, and nil.to_s is "", so return [] if wanted.empty? handles nil, blank and spaces alike.

  4. A deliberate tie-breakcounts.min_by { |author, count| [-count, author] }.first

    With the key [-count, author], the highest count comes first and, on a tie, the alphabetically first name does. Matz wins with two books. The .first after min_by takes the name out of the [author, count] pair. An empty library has empty counts, so the method returned nil earlier.

  5. Words that survive Unicodetext.to_s.downcase.scan(/[\p{L}\p{M}\p{N}']+/) { |word| counts[word] += 1 }

    \p{L} matches letters, \p{M} combining marks and \p{N} digits. Without \p{M}, Myanmar words are cut at their vowel signs and asat marks. Calling scan with a block avoids an intermediate array, and downcase makes "Ruby" and "ruby" one word.

  6. Counting with a defaultcounts = Hash.new(0)

    The default of 0 makes freq["missing"] return 0 without storing the key, so freq.key?("missing") is false, while freq.fetch("missing") would raise KeyError. The default stays attached to the returned hash, so remember it when other code reads that hash.

  7. Enumerator when no block is givenreturn to_enum(:yield_even_numbers, numbers) unless block_given?

    Without a block it returns an Enumerator that will call the method again, so yield_even_numbers([1, 2, 3]).to_a or .map works. With a block it carries on, skips elements that are not Integers (nil, 2.0, "8") with next, and returns how many it yielded.

You should see
Ruby Basics by Matz
More Ruby by Matz
[]
[]
Most prolific: Matz
nil
Rejected: already in the library: RUBY BASICS by matz
ruby=2 is=2 fun=1 and=1 easy=1
0
false
{}
{"မြန်မာစာ" => 2, "ရေးတယ်" => 1}
2
4
6
yielded 3 numbers
[2, 4, 6]
[-40, 0]
[]

Hash.new(0), Hash.new([]) and tally

The three kinds of Hash default look alike but behave differently. Hash.new(0) is safe for numbers, because += assigns a new number instead of changing the old one. With a mutable default such as an Array, << changes the very object that was handed out and stores nothing in the hash. The snippet below shows the trap, the block form that fixes it, and tally side by side.

hash_defaults.rb
shared = Hash.new([])
shared[:a] << 1
shared[:b] << 2
p shared                  # {} - nothing was stored
p shared[:anything]       # [1, 2] - the one shared default array

safe = Hash.new { |hash, key| hash[key] = [] }
safe[:a] << 1
safe[:b] << 2
p safe                    # {a: [1], b: [2]}

counts = %w[ruby is fun ruby].tally
p counts                  # {"ruby" => 2, "is" => 1, "fun" => 1}
p counts["nope"]          # nil - tally returns a plain Hash with no default

Remember one rule: use Hash.new(value) when the default is something that cannot be changed (a number, nil, a symbol) and the block form when it is a mutable object (an array, a hash, a string). For plain counting, tally is the shortest.

What yield really does

yield calls the block and returns the block's last value, which is exactly how methods like map work. The method itself does not know what to do with each item; it only hands the item over and leaves the decision to the caller. Yielding and returning an array are two different designs: yielding streams items without building an array, which helps with large or endless data, while returning an array is easier to test.

my_map.rb
def my_map(items)
  return to_enum(:my_map, items) unless block_given?

  result = []
  items.each { |item| result << yield(item) }
  result
end

p my_map([1, 2, 3]) { |n| n * 10 }     # yield returns the block's value
p my_map([1, 2, 3]).with_index.to_a    # no block: an Enumerator you can chain

In real projects

In real projects

Everything in these exercises appears in real Ruby code. A model class with validation and equality is the base of every Rails model and domain object, and defining == and hash correctly is what makes uniq, include? and Hash keys behave. Collections that include Enumerable are how Ruby libraries expose lists without exposing arrays. Hash counters turn up in log analysis, analytics ("page views per URL") and spell checkers.

Methods that take a block are the Ruby way of letting the caller customise behaviour: File.open { |f| ... } closes the file for you, and so do Array#each, Dir.glob { } and test frameworks that run a block of assertions. Methods that return an Enumerator when called without a block, such as each_slice and each_with_index, are what let you chain map or with_index. Following that convention makes your own methods feel native to Ruby users.

Common mistakes

Common mistakes

Comparing the object instead of its attribute

In the select block of find_by_author, writing book == name instead of book.author == name compares a Book with a String, which is never equal. The result is an empty array and no error. And "matz" does not equal "Matz", so downcase both sides before comparing.

The shared default of Hash.new([])

Writing counts = Hash.new([]) and then counts[word] << word stores nothing in the hash; it piles every word into the one default array. Printing counts shows {}, while counts["anything"] returns the array holding every word. Use Hash.new { |hash, key| hash[key] = [] }.

Calling yield without checking block_given?

Calling the method without a block raises LocalJumpError: no block given (yield) on Ruby 4.0.9 the moment execution reaches the yield. The error appears at the yield line, not at the call, and a list without any even number hides the bug completely. Check block_given? at the top and return an Enumerator.

Defining == without eql? and hash

If Book defines only ==, include? finds an equal book correctly, but uniq keeps both books and a Hash lookup by an equal book finds nothing. Working in one place and failing in another is hard to track down. Whenever you define ==, define eql? and hash in the same breath.

Mini challenge

Search titles with and without a block

Add find_by_title(keyword) to a library. It returns the books whose title contains the keyword, ignoring case. A blank or nil keyword returns an empty array. When a block is given, it yields each match instead of returning an Array, and returns how many matches it yielded.

  • Match anywhere in the title, ignoring upper and lower case
  • Always return an Array when no block is given (never nil)
  • A blank or nil keyword matches nothing
  • With a block: yield each match in library order and return the number of matches
find_by_title.rb
# Reuse Book and Library from the lesson, then add this method.
class Library
  def find_by_title(keyword)
    # TODO: normalise the keyword (nil and blank must match nothing)
    # TODO: pick the books whose title includes it, ignoring case
    # TODO: with a block, yield each match and return how many there were
    # TODO: without a block, return the Array of matches
  end
end

Expected: Searching "ruby" prints three titles, and the size for "RUBY" is 3. "python", " " and nil give []. Finally, searching "design" with a block prints one found: line followed by yielded 1 book(s).

Show hint

keyword.to_s.strip.downcase turns nil and spaces into the same empty string. Collect the matches into an Array with select first, then check block_given?: return the Array straight away when there is no block, otherwise yield each one and return the size.

Show solution
find_by_title.rb
# A trimmed stand-in for the lesson's Book keeps this file short.
Book = Struct.new(:title, :author)

class Library
  include Enumerable

  def initialize(books)
    @books = books
  end

  def each(&block)
    @books.each(&block)
  end

  # Without a block: an Array of matches (never nil). With a block: yields each
  # match in library order and returns how many were yielded.
  def find_by_title(keyword)
    wanted = keyword.to_s.strip.downcase
    matches = wanted.empty? ? [] : select { |book| book.title.downcase.include?(wanted) }
    return matches unless block_given?

    matches.each { |book| yield book }
    matches.size
  end
end

library = Library.new([
  Book.new("Ruby Basics", "Matz"),
  Book.new("Programming Ruby", "Dave Thomas"),
  Book.new("Eloquent JavaScript", "Marijn Haverbeke"),
  Book.new("Practical Object-Oriented Design in Ruby", "Sandi Metz"),
])

puts library.find_by_title("ruby").map(&:title)
p library.find_by_title("RUBY").size
p library.find_by_title("python")
p library.find_by_title("   ")
p library.find_by_title(nil)

count = library.find_by_title("design") { |book| puts "found: #{book.title}" }
puts "yielded #{count} book(s)"

Quick quiz 1 / 3

A method uses Hash.new([]) and runs counts[word] << word for "a" and for "b". What does counts contain afterwards?

Quick quiz 2 / 3

A method calls yield for each even number but never checks block_given?. When does it raise LocalJumpError (no block given (yield))?

Quick quiz 3 / 3

Book defines == (on title and author) but not eql? or hash. When book1 == book2, what does [book1, book2].uniq do?

What to remember

  • Decide each method's promise (return type, empty and nil behaviour, tie rule) before writing the body
  • Define eql? and hash whenever you define ==, or uniq and Hash keys will disagree with it
  • Search methods return an Array; count with Hash.new(0) or tally and avoid Hash.new([])
  • A method that yields should check block_given? and return an Enumerator with to_enum when no block is given
  • Break ties on purpose with a sort key such as [-count, name]

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Practice Exercises 2 | Thuta Learning