From: "David A. Black" Date: 2008-09-09T20:53:30+09:00 Subject: Re: Why is Ruby dynamic? Hi -- On Tue, 9 Sep 2008, Phlip wrote: > David Masover wrote: > >> A nitpick, but... string evals considered harmful! > >>> eval ' > >> I always loved define_method. > > I recently tried define_method and it didn't work, so I fell back to eval. > (Note to the newbs: Try things the most progressive way possible, such as a > fixed version of Dave's version of my example, before trying a hack...) > > Here's the lines, from inspect_sql: > > def self._decorate_explainers(explains) #:nodoc: > def explains.find_statements(regexp) > return AssertEfficientSql._decorate_explainers(select{|explanation| > explanation[:statement] =~ regexp > }) > end > > (_multiples + _singulars).each do |rollup, explainer| > eval "def explains.#{rollup}; map{|q|q[:#{rollup}]}.flatten.uniq; end" > end > > return explains > end > > For the eval line, I first tried explains.define_method, and it didn't work. > Instead of researching why, or finding a kindler gentler system, I whipped > out eval and put a bullet thru the problem. define_method is a private instance method of Module, so a typical use follow something like this path: c.class_eval { define_method(m) {|x| puts x } } > It's the shortest possible eval, anyway! > > Also I think you can't say 'def foo; def bar; end; end' - the def is in > method-space, not class-space. You can nest def's, but the nested one (once the outer one is executed) becomes an outer one: class C def x def y puts "Hi from y" end end end c = C.new c.x c.y # Hi from y d = C.new d.y # Hi from y David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!