Brian Schr?der wrote:
> On 19/11/05, Todd <toddkennethbenson / yahoo.com> wrote:
> > Hello, just 2 simple questions...
> >
> > 1. Why is it that you cannot have an iterator nested inside a
> > conditional loop?  I'm sure there's a good reason, but it escapes me.
> >
>
> As james said, you can.
>
> > 2. Is it possible in Ruby, from within a block, to modify variables
> > that belong to the calling object?  Something similar to Array#map!  Or
> > must this be done in C?
> >
>
> Array.map! could be implemented like this. (In reality its part of
> Enumerable, but that does not matter here)
>
> class Array
>   def map!(&block)
>     changed = false
>     self.each_with_index do | element, index |
>       self[index] = block[element]
>       changed ||= (self[index] == element)
>     end
>     if changed
>       self
>     else
>       nil
>     end
>   end
> end
>
> or even more concise
>
> class Array
>   def map!(&block)
>     changed = nil
>     self.each_with_index do | element, index |
>       changed ||= ((self[index] = block[element]) == element)
>     end
>     self if changed
>   end
> end
>
> but the middle line would I would consider to be golfed too much and
> badly readable, though I like the last line.
>
> cheers,
>
> Brian

OK, maybe I'm going about it the wrong way.  I specified it wrong in
the original post anyway.  What I want to do is have the block be able
to modify the variables in the method that's yielding to it.

Like:

def foo
  a = 1
  yield
  #block does something with a, such that this a is now a new value,
say add 1
  a
end

foo { #some code here }

=> 2

After looking at your code, I think I can accomplish this more
elegantly (by inheriting from Array).  But out of curiosity, is it
possible to do the above?

Thanks,
Todd