On May 1, 2008, at 1:30 AM, Thomas Hafner wrote:
> Hello,
>
> with a function like that
>
>  def let(*a)
>    yield(*a)
>  end
>
> the scope of variables can be limited, e.g. like this:
>
>  let {
>    x = "foo"
>    # ... do something with x ...
>    # here's the end of scope of x
>  }
>  # ...
>  let {
>    x = "bar" # this is another, different x
>    # ... do something with x ...
>  }
>
> Is there already a standard means working like this? If it's a
> standard library function, what's its name?


the simplest way is to use instance_eval

cfp:~ > cat a.rb
instance_eval {
   x = 'foo'
   p x
}

p x rescue :no_x

instance_eval {
   x = 'bar'
   p x
}

p x rescue :no_x



cfp:~ > ruby a.rb
"foo"
"bar"


if you prefer you can do

   class Object
     alias_method "scope", "instance_eval"
   end


and then

scope{ x = 42; p x }

etc.



a @ http://codeforpeople.com/
--
we can deny everything, except that we have the possibility of being  
better. simply reflect on that.
h.h. the 14th dalai lama