If method does not exist, call the default one : method_missing « Reflection « Ruby






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

 








Related examples in the same category

1.Convert all system command to all class method
2.Responding to Calls to Undefined Methods
3.Override method_missing method to provide meaningful error message
4.Create a new class and override the method_missing method
5.Create new method dynamically