不确定我是否添加了任何新内容,但决定显示一个非常简短的代码,我希望我能在答案中找到它以快速显示可用选项。这里没有@shelvacu 所说的枚举器。
class Test
def initialize
@data = [1,2,3,4,5,6,7,8,9,0,11,12,12,13,14,15,16,172,28,38]
end
# approach 1
def each_y
@data.each{ |x| yield(x) }
end
#approach 2
def each_b(&block)
@data.each(&block)
end
end
让我们检查一下性能:
require 'benchmark'
test = Test.new
n=1000*1000*100
Benchmark.bm do |b|
b.report { 1000000.times{ test.each_y{|x| @foo=x} } }
b.report { 1000000.times{ test.each_b{|x| @foo=x} } }
end
结果如下:
user system total real
1.660000 0.000000 1.660000 ( 1.669462)
1.830000 0.000000 1.830000 ( 1.831754)
这意味着 yield 比 &block 我们已经知道的要快一点。
更新:这是 IMO 创建 each 方法的最佳方式,该方法还负责返回枚举器
class Test
def each
if block_given?
@data.each{|x| yield(x)}
else
return @data.each
end
end
end