From: Space Ship Traveller Date: 2009-09-04T12:18:31+09:00 Subject: Re: Is Passing a Binding with Parameters Possible? --Apple-Mail-55-996469042 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=us-ascii; format=flowed; delsp=yes I like lmgtfy: http://lmgtfy.com/?q=Binding+of_caller Kind regards, Samuel On 4/09/2009, at 9:03 AM, John Sikora wrote: > Does anyone know how to pass a binding using parameters instead of a > code block? Is it even possible? > > For various reasons (primarily syntactic sugar implementation), I need > to eval a string in one method in the scope of another method. The > following is a simplified version of the code (which works): > > > def called_method(*parameters, &code_block) # code_block handler > ignored. > parameters.each do |parameter| > eval(parameter, code_block.binding) > end > end > > def calling_method > a = 3 > string_to_evaluate = 'puts a' > called_method(string_to_evaluate){} > end > > calling_method # => 3 > > > Obviuosly, this requires a code block for 'called_method'. In the > actual > code, whenever eval is used, parameters are always present. Code > blocks > are optional. So when a code block is not needed, the empty code block > has to be included. > > No big deal, but it would be nice to be able to use the parameters to > pass the binding (since they are always present when eval is used). > Such > as: > > > def called_method(*parameters, &code_block) # code_block handler > ignored. > parameters.each do |parameter| > eval(parameter, parameters.binding) > end > end > > def calling_method > a = 3 > string_to_evaluate = 'puts a' > called_method(string_to_evaluate) > end > > calling_method # => in 'called_method' private method 'binding' > called... > > > So I guess .binding is a private method for objects other than code > blocks, in this case an Array. If I change 'parameters.binding' to > 'binding', it (of course) does not give the right binding, resulting > in > variable 'a' being undefined. I have tried some other code snippets > that > I thought might work, but to no avail. > > I know a binding could be created inside of calling_method and it > could > be could be passed, but the way it is now with the empty braces is > easier, which is the point of syntactic sugar. > > Can it be made even easier by passing the binding 'automatically' with > the parameters instead of a code block? > > John S. > -- > Posted via http://www.ruby-forum.com/. > --Apple-Mail-55-996469042--