2009-08-05

dynamically defined methods in ruby

I've been playing around with dynamically creating methods today and it's mighty cool stuff. here's a very contrived demo class:
class Demo
METHODS=["one","two","three","four"]
METHODS.each { |name|
define_method("method_#{name}") do
|arg|
puts "this method is named method_\"#{name}\" and you gave me the arg \"#{arg}\""
end
}
end


and me using it in irb
irb> demo = Demo.new
=> #<Demo:0xb7be8900>
irb> demo.method_one("this is an arg")
this method is named "method_one" and you gave me the arg "this is an arg"
=> nil
irb> demo.method_two("this is an arg")
this method is named "method_two" and you gave me the arg "this is an arg"
=> nil
irb> demo.method_four("this is another arg")
this method is named "method_four" and you gave me the arg "this is another arg"
=> nil