Q:

Yield n times in a method not working?

An example of what I'm trying to do is probably best:
def repeater(n = 1)
  n.times { yield }
end

By default, repeater will go through the block given once. However, I want it to go through the block multiple times if given n > 1. For some reason the above code doesn't work.
For instance:
I would expect this to result in 64, but instead it returns 5:
y = 2
repeater(5) { y *= 2 }

Why is this happening? Where am I going wrong? I'm fairly new to yield, and don't understand it entirely (clearly).

A:

The problem is that the return value of repeater is the return value of times, which will always be n, so you should interrogate the resulting value of y itself instead:
y = 2
repeater(5) { y *= 2 }  #=> 5
y  #=> 64

If you want repeater to actually return the final result, you could reduce over a Range:
def repeater(n = 1)
  (0..n).reduce { yield }
end

y = 2
repeater(5) { y *= 2 }  #=> 64

