On May 2, 2004, at 3:09 AM, Kristof Bastiaensen wrote:

> Hi,
>
> On Sun, 02 May 2004 03:08:36 +0900, Mark Hubbart wrote:
>>    binding.local(:a) = 23  #=> 23
>>    a                       #=> 23
>>    binding.local(:a) += 19 #=> 42
>>    a                       #=> 42
>>
>
> I wonder how you could make this work.  binding.local(:a)
> would have to return something that could be used as a
> lvalue.  I could be a reference, but the reason to have
> these methods would be to avoid them.
> Another way to do this:
>
> binding.local(:a).value = 23
> binding.local(:a).value += 19
>
> binding.local(sym) would then return something like
> a Variable class.  It will still be possible to change
> the value of a variable, but not without participation
> of the calling scope.

I see. I momentarily forgot that while you can use methods as lvalues, 
you have to choose between lvalue and method call; you can't assign to 
it if you use the parens. I'm scrambling now for a replacement that I 
like...

Perhaps:

binding[:a] = 23
binding[:a] += 19

Here's some rather simple code that will do it:

class Binding
   def [](sym)
     eval(sym.to_s, self)
   end
   def []=(sym, val)
     code = "#{sym} = ObjectSpace._id2ref #{val.id}"
     eval(code, self)
   end
end

I agree that in most cases this should be avoided. However, there are 
some cases where bindings are the only way of getting things done. irb, 
for example, makes extensive use of programming practices that would 
otherwise be looked upon as horrific. :) Serious violation of scoping 
rules.

>> also:
>>
>>    binding.eval{ self }    #=> main
>>
>
> Also here I would remove the eval.  Maybe binding.get_self or
> binding.current_object?

I guess there could be methods added for that. But I think the eval 
thing should be there for more general purpose stuff. It would be 
easier to remember one eval method than five fetching methods.

Also, it would be better to call it something other than 'eval' I 
suppose. #binding_eval?

By allowing a simple way of eval'ing code within a binding like that, 
you end up with a very flexible way of working with bindings.

>> .. would be nice. I dislike having to eval strings when I need to do
>> some work within a certain binding; and I suppose that code blocks 
>> will
>> compile nicer, especially when we get a VM.
>
> Yes, I agree.  Maybe we could pack it up in a RCR?

I think that would be a good idea; Object#instance_eval takes code 
blocks; why not Kernel#eval? If Kernel#eval supported code blocks, it 
would be trivial to define Binding#binding_eval.

>
> Kristof
>