Hi. I have a recursive function (it calls itself) that accepts a block.
def arecursor(param)
[...]
yield var
[...]
if (some condition)
arecursor(another_var)
end
[...]
end
When the function is first called, the yield statement succeeds. But
after the function calls itself, it looses the block. How do I make the
block persistant-- can I do something like this::?
You can make the block a normal parameter using the & operator.
def arecursor(param, &block)
[...]
block.call(var)
[...]
if (some condition)
arecursor(another_var,&block)
end
[...]
end
T.
You can also do it with yield, but it doesn't improve performance.
(Using yield instead of & is faster in some cases, because no Proc
object is created.)
def recurse_n_times_using_yield(n)
return if n == 0
yield n
recurse_n_times_using_yield(n-1) do |nn|
yield nn
end
end
recurse_n_times_using_yield(10) {|n| p n}
def recurse_n_times_using_proc(n, &block)
return if n == 0
yield n
recurse_n_times_using_yield(n-1, &block)
end
recurse_n_times_using_proc(10) {|n| p n}
require 'benchmark'
Benchmark.bmbm do |bm|
bm.report 'using_yield' do
recurse_n_times_using_yield(1000) {|n|}
end
bm.report 'using_proc' do
recurse_n_times_using_proc(1000) {|n|}
end
end