If you want to use this sort of idiom, try this example which doesn't
require any changes to the language:
require 'context' #See below...
x = 0
{
my = Context.new
my.x = 7
my.x #-> 7
}
x #-> 0
Here's the code for Context (suggestions welcome, I'm sure there are better
ways to do this). You can probably use something like this to suit your
needs. Also, if you want immutable names, do this:
my = Context.new(false)
my.x = 2
my.x # -> 2
my.x = 5 #-> RuntimeError: Can't reassign variable
#context.rb
class Context
@@method_template = %q{
def X
@names['X']
end
if @mutable then
def X=(val)
@names['X'] = val
end
else
def X=(val)
raise RuntimeError, "Can't reassign variable"
end
end
}
def initialize(mutable = true)
@names = Hash.new
@mutable = mutable
end
def method_missing(sym, *args)
attrib = sym.to_s
if attrib[-1,1] != "="
raise NameError, "undefined method '#{attrib}' for object #{to_s}"
end
prop_name = attrib[0, (attrib.length - 1)]
new_meth_def = @@method_template.gsub(/X/, prop_name)
instance_eval(new_meth_def)
@names[prop_name] = args[0]
end
end
Hope that helps,
Bryn
-----Original Message-----
From: cjon / sapphire.engin.umich.edu
[mailto:cjon / sapphire.engin.umich.edu]
Sent: Tuesday, March 06, 2001 9:10 PM
To: ruby-talk / ruby-lang.org; ruby-talk / netlab.co.jp
Subject: [ruby-talk:12207] Re: FEATURE REQUEST: 'my' local variables
Leo Razoumov (see_signature / 127.0.0.1) wrote:
> # PROPOSED FEATURE:
> x = 0 #line_1
> {
> my x = 7 # new varible 'x' shadowing 'x' from line_1
> x # -> 7
> }
> x # -> 0
This seems to me like it would be very useful.
Cullen J O'Neill
--
cjon / engin.umich.edu