Dumaiu
7/22/2006 8:11:00 PM
Erik Veenstra wrote:
> Can somebody explain me, in detail, the differences between
> aModule.instance_eval, aModule.module_eval and
> aModule.class_eval?
>
> I'm especially interested in the differences in context.
>
....
I think inspect() and object_id() confuse the issue, and trying to use
instance_eval() at module scope is about as much fun as putting a
screwdriver through your eye. My own views are as follows:
module_eval() is intended for defining methods dynamically, and its
receiver should be of class Module. Given
module M; end
mod = M # or some other module
I would use
m.module_eval {
def foo; end
}
as a faster, cleaner way of accomplishing
eval <<-EOS
module #{m.to_s}
def foo; end
end
EOS
which is hampered by its reliance on a string eval().
On the other hand, I see instance_eval() as primarily useful for
*calling* a blockful of methods, with a dynamically-determined
receiver. Say you have a bunch of stuff you want some object to
do--e.g., you know it'll be Enumerable, so you have some Enumerable
methods--
module Enumerable
def func()
any? whatever
sort
to_a
end
end
enum.func()
but then you realize that you might want to use this more generally,
not just on Enumerable objects. So you wrap it:
func = proc do
any? whatever
sort
to_a
end
and when you want somebody to call it, use
obj.instance_eval &func
The alternative would be
func = proc do |receiver|
receiver.any? whatever
receiver.sort
receiver.to_a
end
func.call(obj)
which is a less elegant factorization.
....
>
> I'll switch back to good old Lisp...
>
> Good bye, brave Ruby people...
>
> It was a nice time...
>
> So long...
>
Bye.