user1297102
user1297102

Reputation: 661

Ruby, pass/return a counter in a recursive code block

How would I pass an index through a series of code blocks?

# i'm not sure how to set this up
def call(index=0, &block)    # index here is likely not needed
    yield (index+1) # or block.call(index)
end

call{call{call{}}}

should give a total count (3) and the count at each call preferably without having to explicitly use call { |i| call{ |i| } }

Upvotes: 0

Views: 354

Answers (1)

Ivan Antropov
Ivan Antropov

Reputation: 414

Try this variant:

def call(index = 0)
  if block_given? and (res = yield(index + 1)) != nil
    res + 1
  else
    index + 1
  end
end

Upvotes: 2

Related Questions