×

ruby · level 3 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

catches calls to methods that do not exist.

When you call a method an object does not have, Ruby does not give up straight away. First it calls method_missing on that object, passing the method's name and its arguments, gathered by into an array. The built-in version raises NoMethodError. Write your own and you can answer instead, with a .

Rails uses this for finders such as find_by_city("York"). Check the name, handle only the pattern you expect, and hand everything else to super, the built-in version, so real typos still raise NoMethodError. Answering every call would hide bugs.

class Contacts
  def initialize(people)
    @people = people
  end
  def method_missing(name, *args)
    return super unless name.start_with?("find_by_")
    field = name.to_s.sub("find_by_", "").to_sym
    @people.find { |person| person[field] == args[0] }
  end
end
book = Contacts.new([{ name: "Ana", city: "Leeds" }, { name: "Raj", city: "York" }])
p book.find_by_city("York")
p book.find_by_name("Ana")

The name arrives as a symbol, such as :find_by_city, so to_s turns it into text you can trim.