Subclass Array class
class Library < Array
def add_book(author, title)
self << [author, title]
end
def search_by_author(key)
reject { |b| !match(b, 0, key) }
end
def search_by_author_or_title(key)
reject { |b| !match(b, 0, key) && !match(b, 1, key) }
end
:private
def match(b, index, key)
b[index].index(key) != nil
end
end
l = Library.new
l.add_book("author 1", "title 1")
l.add_book("author 2", "title 2")
p l.search_by_author("author 1")
p l.search_by_author_or_title("title 1")
Related examples in the same category