Let's think this through for a second
This lesson is tougher than Exercises 1, combining OOP class design, blocks/yield, and Hash data structures into tasks that mix things together. It's a chance to practice the class-object, initialize, getters-setters, and blocks concepts from the Advanced chapter in something close to a real-world scenario. Work through the tasks in order and you'll build up practice step by step, from class design all the way to block-based iteration.
Exercises
Task 1: Build a Book class with title and author attributes using attr_accessor and initialize. Task 2: Build a Library class with an add_book(book) method that adds Book objects to a @books array — then write a find_by_author(name) method that uses a .select block to return the list of books matching the given author name. Task 3: Write a word_frequency(text) method that uses Hash.new(0) to count how many times each word appears in a sentence. Task 4: Write a yield_even_numbers(numbers) { |n| ... } method that yields each even number in the array to the block passed in by the caller.
Code Example
class Book
attr_accessor :title, :author
def initialize(title, author)
@title = title
@author = author
end
end
class Library
def initialize
@books = []
end
def add_book(book)
@books << book
end
def find_by_author(name)
# TODO: block/select သုံးပြီး author name နဲ့ ကိုက်ညီတဲ့ book တွေကို ပြန်ပေးပါ
end
end
def word_frequency(text)
# TODO: Hash.new(0) သုံးပြီး word တစ်လုံးချင်းစီရဲ့ အကြိမ်ရေကို ရေတွက်ပါ
end
def yield_even_numbers(numbers)
# TODO: block ကိုသုံးပြီး even number တစ်ခုချင်းစီအတွက် yield ပေးပါ
end
library = Library.new
library.add_book(Book.new("Ruby Basics", "Matz"))
p library.find_by_author("Matz")
p word_frequency("ruby is fun and ruby is easy")
yield_even_numbers([1, 2, 3, 4, 5, 6]) { |n| puts n }find_by_author should return a list of Book objects, word_frequency should return a Hash like {"ruby"=>2, "is"=>2, ...}, and yield_even_numbers should print numbers like 2, 4, 6 with puts.5-Minute Challenge
Write a new find_by_title(keyword) method on the Library class that uses a .select block to return books whose title contains the keyword — try it in 5 minutes.
One Quick Warning
Checking block_given? before using yield in a method makes your error handling better — keep this pattern in mind when writing production code.