From: Ehsanul Hoque Date: 2009-11-20T14:25:20+09:00 Subject: Re: eval behaves differently inside a method definition... --_d36c78b8-4b3d-49b1-a8bd-516cb1df93e8_ Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi Tim. > #lets give strings the ability to evaluate theirselves as if in irb. > >> class String > >> def irb > >> eval self > >> end > >> end > =3D> nil > >> "puts 'look at me'" > =3D> "puts 'look at me'" > >> "puts 'look at me'".irb > look at me > =3D> nil >=20 > #good looks like strings can interpret theirselves. But how about this > case? >=20 > >> "class Pumpkin=3Bdef pie=3Bputs 'yum'=3Bend=3Bend".irb > =3D> nil > >> Pumpkin.new > NameError: uninitialized constant Pumpkin > from (irb):287 > from /usr/local/bin/irb:12:in `
' >=20 > #not flying. Is it a problem with the string? Try with eval of the > same string: >=20 > >> eval "class Pumpkin=3Bdef pie=3Bputs 'yum'=3Bend=3Bend" > =3D> nil > >> Pumpkin.new > =3D> # >=20 > No problem evaluating the class definition in a string. So eval > behaves differently inside a method definition. It's not that eval behaves differently inside a method definition. It's jus= t that it takes into account the scope in which it was called. When inside the String class=2C or any other class for that matter=2C if yo= u create another class=2C you can't call it from outside the parent class w= ithout referring to the parent. So for example: class String class Pumpkin def pie puts 'yum' end end end Pumpkin.new #=3D> NameError: uninitialized constant Pumpkin String::Pumpkin.new #=3D> # The parent class effectively acts as a namespace for the subclass. BTW=2C I= really don't think I should call it a "subclass"=2C as that seems to imply= inheritence - none of that here. Maybe someone else can tell us the proper= name for this structure/pattern. So you probably understand the issue by now=2C eval within the String class= (whether or not inside a method definition) creates a "subclass" of sorts= =2C and hence you can't call it directly outside. If you tried to call "Str= ing::Pumpkin.new" instead after using your "irb" method=2C it would have wo= rked (try it out). Alternately=2C you could have done it this way: class String def irb eval self end end "class ::Pumpkin=3Bdef pie=3Bputs 'yum'=3Bend=3Bend".irb Pumpkin.new.pie Hope that helps. - Ehsan =20 _________________________________________________________________ Windows 7: It works the way you want. Learn more. http://www.microsoft.com/Windows/windows-7/default.aspx?ocid=3DPID24727::T:= WLMTAGL:ON:WL:en-US:WWL_WIN_evergreen:112009v2= --_d36c78b8-4b3d-49b1-a8bd-516cb1df93e8_--