From: michael libby Date: 2002-08-24T22:56:08+09:00 Subject: Re: eval in class method -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Saturday 24 August 2002 07:22, michael libby wrote: > irb(main):011:0> class FooBar > irb(main):012:1> def rebaz > irb(main):013:2> eval("class FooBar\ndef baz\nputs > 'foobar:rebaz'\nend\nend") > irb(main):014:2> end > irb(main):015:1> end > nil > irb(main):016:0> f.rebaz > nil > > So far nothing seems amiss. Instead of doing eval from main script, > wrote rebaz method to do eval as instance method. > > irb(main):017:0> f.baz > foobar:new baz > nil > > Sigh. After calling #rebaz which I thought would have changed #baz, #baz > still acts the same-- even though, except for scope/context, the eval > statement was the same exact statement as I used before, where #baz did > change. [answering my own question here...] What I found to work as an alternative was to write a root level eval function and call that from within the class: #!/usr/bin/ruby -w def root_eval(eval_string) eval(eval_string) end class FooBar def baz puts "foobar:baz" end def rebaz(s) root_eval(s) end end f = FooBar.new f.baz f.rebaz("class FooBar\ndef baz\nputs 'foobar:bitz'\nend\nend") f.baz Output: chandler@greyhound:~/ruby$ ruby root_eval.rb foobar:baz (eval):2: warning: discarding old baz foobar:bitz chandler@greyhound:~/ruby$ Which is perfect! Now my text editor can edit and reload its own code without a restart. -michael ++++++++++++++++++++++++++++++++++++++++++ Michael C. Libby public key: http://www.ichimunki.com/public_key.txt web site: http://www.ichimunki.com ++++++++++++++++++++++++++++++++++++++++++ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE9Z5BC4ClW9KMwqnMRAm6BAKCcElzlUVtC68cZoQ5hEbMt548vZACePCSw z4d9UE/q/IIqFPyf0gNeJYY= =dtNh -----END PGP SIGNATURE-----