Mega Code Archive

 
Categories / Ruby / Reflection
 

If method does not exist, call the default one

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   def method_missing(m, *args)     search_by_author_or_title(m.to_s)   end end l = Library.new("author","title") p l.a p l.b p l.c