This is useful if you are trying to create class methods metaprogramatically:
def self.create_methods(method_name)
# To create instance methods:
defi
Derived from: Jay and Why, who also provide ways to make this prettier.
self.create_class_method(method_name)
(class << self; self; end).instance_eval do
define_method method_name do
...
end
end
end
Update: from VR's contribution below; a more concise method (as long as you're only defining one method this way) that is still standalone:
self.create_class_method(method_name)
(class << self; self; end).send(:define_method, method_name) do
...
end
end
but note that using send() to access private methods like define_method() is not necessarily a good idea (my understanding is that it is going away in Ruby 1.9).