Just curious... is there any difference between using define_method and
def in this case? =A0It seems they achieve the same effect. =A0Why would = one
be preferred over the other?
?> =A0 =A0 define_method
test) do
?> =A0 =A0 =A0 puts "Testing!"
Testing!
=3D> nil
Testing!!
=3D> nil
The difference is that def starts a new scope, it's not a closure, so
it doesn't see its surrounding scope. In the following case (as well
as the original case by the OP), the local variable 'a' is seen in the
block passed to define_method, but not to the body of the 'def'
keyword, since it's not a closure:
irb(main):001:0> class A; end
=3D> nil
irb(main):002:0> a =3D 3
=3D> 3
irb(main):003:0> A.class_eval do
irb(main):004:1* define_method
go) do
irb(main):005:2* puts a # this a is the a outside the class_eval
irb(main):006:2> end
irb(main):007:1> end
=3D> #<Proc:0xb788d530@(irb):4>
irb(main):008:0> A.new.go
3
=3D> nil
irb(main):009:0> A.class_eval do
irb(main):010:1* def no_go
irb(main):011:2> puts a #this one is undefined
irb(main):012:2> end
irb(main):013:1> end
=3D> nil
irb(main):014:0> A.new.no_go
NameError: undefined local variable or method `a' for #<A:0xb7870584>
from (irb):11:in `no_go'
from (irb):14
from :0
Hope this helps,
Jesus.