Subclass Array class : inheritance « Class « Ruby






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

1.Basing one class on another is called inheritance.
2.Extends class
3.how inheritance works in code form
4.Basing One Class on Another: a Demo
5.different types of people
6.Structuring Your Pets Logically
7.If the class Name were in a different file, you would just require that file first
8.Add new constructor
9.Module and class hierarchy