From: "David A. Black" Date: 2008-04-20T21:50:20+09:00 Subject: Re: Executing code in a variable Hi -- On Sun, 20 Apr 2008, christiantheilhave@gmail.com wrote: > On Apr 20, 11:43 am, Zangief Ief wrote: >> Hello, >> >> I have a Ruby code stocked into a Ruby variable like this: >> >> buffer = ' puts "Hello World!" ' >> >> Is there a way for execute the current code by using buffer variable ? >> >> Thanks >> -- >> Posted viahttp://www.ruby-forum.com/. > > Sure, you can use eval, eg. > > irb(main):002:0> eval 'puts "Hello world"' > Hello world > => nil > > However, eval should be usually avoided. Instead Ruby has the methods > instance_eval, class_eval and module_eval, which works the same as > eval but the argumented is executed in the scope of the current object/ > class/module. The main advantage of instance/class/module_eval over eval, though, is that they can take a block and therefore you don't have to evaluate a string. If you do this: obj.instance_eval(str) it's no better or worse, from the point of view of safety, than using eval. David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!