From: "T. Onoma" Date: 2003-11-27T02:26:24+09:00 Subject: Re: Controlled block variables On Wednesday 26 November 2003 03:57 pm, Dan Doel wrote: > I actually have wondered in the past why there isn't an #eval that takes > a proc (other than as a binding). > > There's #instance_eval and #module_eval/#class_eval for replacing the > object scope of a Proc, but > there's no way you can do this: > > def foo > a = 4 > b = 5 > > proc { p a; p b } > end > > def bar(p) > a = 7 > b = 8 > > eval p > end > > bar(foo) > > and get 7 and 8 printed. I realize that Proc objects are closures, but > since they're also representations > of sections of code, it would be interesting to be able to switch them > to dynamic scoping for all the > benefits and problems that causes, and using #eval seems like a fairly > clean way of denoting that. this is an interesting means of code evaluation. essentially encapsulating blocks of code to be "opened-up" (like a can of worms ;-) at other points in execution. it is a technique quite capable of replacing methods/functions all together. but there is a severe problem with it: it causes bad headaches with name clashing. this is why methods are used instead. with methods you at least know what is going into them and variables are renamed in transition. for example what if i was using the variable x instead of a? i'd have to set a = x, but what if i was already using a for something else, then i'd have to move a out of the way. and so forth. so what you end up doing instead is def foo a = 4 b = 5 proc { |a,b| p a; p b } end def bar(p) a = 7 b = 8 p.call(a,b) end bar(foo) and you'll get 7 and 8 without the problem sited above. that said, now perhaps someone can explain to me why the #call is need? is there some reason the interpretor can't deal with just p(a,b) couldn't Ruby just give precedence to proc evaluation similiar to local precedence? thanks Dan, -t0