From: Greg Weeks Date: 2007-11-19T09:22:07+09:00 Subject: Re: eval, module_eval, define_method, and all that In this forum, I've mentioned several times that some people don't like "eval". Here is the end of section 11.3.5 from "The Ruby Way": In previous versions of Ruby, we often defined methods at runtime by calling "eval". In essence, "define_method" can and should be used in all these circumstances. "ALL these circumstances". That's strong stuff. Well, I'm ready to bow to authority. But how can I see "define_method" as loveable? How about this: "define_method" is Minimally Magical. Here's what I mean. Given the name "define_method", we naturally expect "foo" and "bar" below to have the same behavior: CONST = "Object" class A CONST = "A" @val = "A" attr_accessor :val def foo [CONST, @val, self] end define_method :bar do [CONST, @val, self] end end a = A.new a.val = "a" p a.foo -> ["A", "a", #] p a.bar -> ["A", "a", #] If "define_method" was not magical, then, within its block argument, the values of CONST and @val and self would be "A" and "A" and A (the class object). The minimal magic required to get the desired answer is to make @val and self refer to the A instance, but leave CONST to scope lexically. And that seems to be what "define_method" does. I personally will follow "The Ruby Way" (second edition). Stand behind me, *eval methods! -- Posted via http://www.ruby-forum.com/.