Ruby,在递归代码块中传递/返回一个计数器

时间:2013-06-05 10:22:10

标签: ruby counter

如何通过一系列代码块传递索引?

# 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{}}}

应该给出总计数(3)和每次通话的计数 最好不必明确使用call {| i |打电话给{| i | }}

1 个答案:

答案 0 :(得分:2)

尝试此变体:

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