Here's an example of an esoteric metaprogramming technique that I mentioned in the comments:
module Foo
instance_eval do
def bar
'baz'
end
end
end
Now call the new method:
Foo.bar
=> 'baz'
instance_eval
's use is unintuitive because it's meant for defining class methods, whereas class_eval
is for instance methods.
There's a similar approach for the technique Cary mentioned (although he used define_method
which is for instance methods versus define_singleton_method
for class methods):
module Foo
define_singleton_method(:bar) do
'baz'
end
end
Calling the method works the same:
Foo.bar
=> 'baz'
But again, these are advanced techniques that you'll never see used in this way, because there are much simpler standard ways of accomplishing the same task (and you gave two examples in your question). If you tried defining all your class methods this way it would be ugly and repetitive and confusing to anyone reading it.
The techniques shown are typically used by code outside the defined module/class so that you can externally manipulate it without having to directly modify the source code for it, sometimes referred to as monkey patching.
For example, if the module is defined with no methods:
module Foo
end
You could in some other code anywhere else say Foo.instance_eval {}
or Foo.define_singleton_method(:bar) {}
and it would apply to Foo
thereafter. This is useful when you want to frustrate the author of Foo
's attempt at encapsulation.
And in case I'm not being clear, the examples I've shown here are what you should not do. They're used when dynamic changes to classes/modules are needed. That's not what you described.