faithfulgeek.org

Agile web development

Fun with method_missing

December 14th, 2007

If you know me, you probably know I’m learning Ruby. It’s an amazing language that just keeps getting better as I learn more. I recently started playing with method_missing, which is a method that is called when the message you are passing to a class does not exist. I wrote the following Hello World example tonight to print “Hello, ” followed by a name, in a unique way.


Hello.Joe # Prints Hello, Joe
Hello.Tom # Prints Hello, Tom
Hello.Katie # Prints Hello, Katie

The code that makes it work:


class Hello
    def self.method_missing(id, *args)
        return "Hello, #{id}" 
    end
end

Hope you and find this at least somewhat useful. If not, at least as much fun as I had writing it!

1 Response to “Fun with method_missing”

  1. Anthony Broad-Crawford Says:

    class Example

    def method_missing(method, *args)
    self.class.instance_eval do
    define_method(method){
       puts "#{method} doesn't exist .... go away" 
    }
    end
    eval("self.#{method}")
    end

    end

    Example.new.some_missing_method

Leave a Reply