case name
when “one”
lambda {x += 1; puts x}
when “two”
lambda {puts x}
end
end
one = f “one”
two = f “two”
The assignment “x = 0” gets executed every time you call f, creating a
new x
each time and initializing that new x to zero.
As far as I can tell, Ruby has no static scope, only dynamic scope,
which,
if I’m right, means there’s no straightforward way to do what you’re
trying.
In Perl, for instance, you could do this:
{
my $x = 0;
sub f
{
my $name = shift;
return sub { $x += 1; print “$x\n”; } if ($name eq ‘one’);
return sub { print “$x\n”; } if ($name eq ‘two’);
}
}
my $one = f(‘one’);
my $two = f(‘two’);
$one->();
$two->();
$one->();
$two->();
And achieve the result you expected, but in Ruby, I don’t know how to
achieve
something similar. As a practical matter, I would just create an object
with
an attribute and use methods on that object in lieu of the closures.