ruby methods that either yield or return Enumerator

后端 未结 4 643
死守一世寂寞
死守一世寂寞 2021-01-31 03:47

in recent versions of Ruby, many methods in Enumerable return an Enumerator when they are called without a block:

[1,2,3,4].map 
#=>         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-31 04:10

    use Enumerator#new:

    class Array
      def double(&block)
        Enumerator.new do |y| 
          each do |x| 
            y.yield x*2 
          end 
        end.each(&block)
      end
    end
    

提交回复
热议问题