ruby methods that either yield or return Enumerator
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 } endend>> [1, 2, 3].double { |x| puts(x) }246 >> ys = [1, 2, 3].double.select { |x| x > 3 } #=> [4, 6]
use Enumerator#new:
class Array def double(&block) Enumerator.new do |y| each do |x| y.yield x*2 end end.each(&block) endend
Another approach might be:
class Array def double(&block) map {|y| y*2 }.each(&block) end end