title: Ruby: define_method vs. def
body: <p>As a programming exercise, I've written a Ruby snippet that creates a class, instantiates two objects from that class, monkeypatches one object, and relies on method_missing to monkeypatch the other one.</p>
  
  <p>Here's the deal.  This works as intended:</p>
  
  <pre><code>class Monkey
  
    def chatter
      puts "I am a chattering monkey!"
    end
  
    def method_missing(m)
      puts "No #{m}, so I'll make one..."
      def screech
        puts "This is the new screech."
      end
    end
  end
  
  m1 = Monkey.new
  m2 = Monkey.new
  
  m1.chatter
  m2.chatter
  
  def m1.screech
    puts "Aaaaaargh!"
  end
  
  m1.screech
  m2.screech
  m2.screech
  m1.screech
  m2.screech
  </code></pre>
  
  <p>You'll notice that I have a parameter for method_missing.  I did this because I was hoping to use define_method to dynamically create missing methods with the appropriate name.  However, it doesn't work.  In fact, even using define_method with a static name like so:</p>
  
  <pre><code>def method_missing(m)
    puts "No #{m}, so I'll make one..."
    define_method(:screech) do
      puts "This is the new screech."
    end
  end
  </code></pre>
  
  <p>Ends with the following result: </p>
  
  <pre><code>ArgumentError: wrong number of arguments (2 for 1)
  
  method method_missing   in untitled document at line 9
  method method_missing   in untitled document at line 9
  at top level    in untitled document at line 26
  Program exited.
  </code></pre>
  
  <p>What makes the error message more bewildering is that I only have one argument for <code>method_missing</code>...</p>