Defining methods dynamically

suggest change

Ruby can change the program while it is running. One way is to define methods dynamically with method_missing.

For example, test whether a number is greater than another with the syntax 777.is_greater_than_123?.

# open Numeric class
class Numeric
  # override `method_missing`
  def method_missing(method_name,*args)
    # test if the method_name matches the syntax we want
    if method_name.to_s.match /^is_greater_than_(\d+)\?$/
      # capture the number in the method_name
      the_other_number = $1.to_i
      # return whether the number is greater than the other number or not
      self > the_other_number
    else
      # if the method_name doesn't match what we want, let the previous definition of `method_missing` handle it
      super
    end
  end
end

When you use method_missing, also teach Ruby that the method exists. On current Ruby, define respond_to_missing?. Overriding respond_to? still works:

class Numeric
   def respond_to?(method_name, include_all = false) 
     method_name.to_s.match(/^is_greater_than_(\d+)\?$/) || super
   end
end

Forgetting that leads to an inconsistent situation: 600.is_greater_than_123? can succeed, while 600.respond_to?(:is_greater_than_123?) returns false.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents