ruby methods that either yield or return Enumerator

后端 未结 4 651
死守一世寂寞
死守一世寂寞 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

    The core libraries insert a guard return to_enum(:name_of_this_method, arg1, arg2, ..., argn) unless block_given?. In your case:

    class Array
      def double
        return to_enum(:double) unless block_given?
        each { |x| yield 2*x }
      end
    end
    
    >> [1, 2, 3].double { |x| puts(x) }
    2
    4
    6 
    >> ys = [1, 2, 3].double.select { |x| x > 3 } 
    #=> [4, 6]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-31 04:30

    Another approach might be:

    class Array
        def double(&block)
            map {|y| y*2 }.each(&block)
        end
     end
    
    0 讨论(0)
  • 2021-01-31 04:33

    easiest way for me

    class Array
      def iter
          @lam = lambda {|e| puts e*3}
          each &@lam
      end
    end
    
    array = [1,2,3,4,5,6,7]
    array.iter
    

    => 3 6 9 12 15 18 21

    0 讨论(0)
提交回复
热议问题