Ruby self.to_enum 求解疑

stephansun · 2014年03月17日 · 最后由 stephansun 回复于 2014年03月17日 · 1690 次阅读

《The Ruby Programming Language》5.3.4 Enumerators 这一节中有段代码

def twice
  if block_given?
    yield
    yield
  else
    self.to_enum(:twice)
  end
end

没看懂,原文中说 You can duplicate this behavior in your own iterator methods by returning self.to_enum when no block is supplied. Here, for example, is a version of the the twice iterator shown earlier that can return an enumerator if no block is provided:

但是这样写有什么实际意义吗?

没有 else 你只能这样用,twice { do somethoing } 上面 else 这样写了之后你可以这样用,e = twice; e.each { do something }

#1 楼 @nowherekai 多谢提点!想通了!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号