Ruby self.to_enum 求解疑

stephansun · March 17, 2014 · Last by stephansun replied at March 17, 2014 · 1692 hits

《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 多谢提点!想通了!

You need to Sign in before reply, if you don't have an account, please Sign up first.