产生或返回 Enumerator 的 ruby 方法 [英] ruby methods that either yield or return Enumerator
本文介绍了产生或返回 Enumerator 的 ruby 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在最新版本的 Ruby 中,Enumerable
中的许多方法在没有块的情况下被调用时返回一个 Enumerator
:
in recent versions of Ruby, many methods in Enumerable
return an Enumerator
when they are called without a block:
[1,2,3,4].map
#=> #<Enumerator: [1, 2, 3, 4]:map>
[1,2,3,4].map { |x| x*2 }
#=> [2, 4, 6, 8]
我想用我自己的方法做同样的事情:
I want do do the same thing in my own methods like so:
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 }
推荐答案
核心库插入保护 return to_enum(:name_of_this_method, arg1, arg2, ..., argn) 除非 block_given?
.在你的情况下:
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]
这篇关于产生或返回 Enumerator 的 ruby 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文