产生或返回Enumerator的ruby方法

时间:2011-08-24 23:05:10

标签: ruby enumerable

在最新版本的Ruby中,Enumerable中的许多方法在没有块的情况下调用时会返回Enumerator

[1,2,3,4].map 
#=> #<Enumerator: [1, 2, 3, 4]:map> 
[1,2,3,4].map { |x| x*2 }
#=> [2, 4, 6, 8] 

我想在我自己的方法中做同样的事情,如:

class Array
  def double(&block)
    # ???
  end
end

arr = [1,2,3,4]

puts "with block: yielding directly"
arr.double { |x| p x } 

puts "without block: returning Enumerator"
enum = arr.double
enum.each { |x| p x }

4 个答案:

答案 0 :(得分:28)

核心库插入一个警卫return to_enum(:name_of_this_method, arg1, arg2, ..., argn) unless block_given?。在你的情况下:

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]

答案 1 :(得分:9)

使用Enumerator#new

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

答案 2 :(得分:2)

另一种方法可能是:

class Array
    def double(&block)
        map {|y| y*2 }.each(&block)
    end
 end

答案 3 :(得分:0)

对我来说最简单的方法

class Array
  def iter
      @lam = lambda {|e| puts e*3}
      each &@lam
  end
end

array = [1,2,3,4,5,6,7]
array.iter

=&GT; 3 6 9 12 15 18 21

相关问题