def any?
if block_given?
method_missing(:any?) { |*block_args| yield(*block_args) }
else
!empty?
end
end
Run Code Online (Sandbox Code Playgroud)
在ActiveRecord的代码中,块中存在的yield语句的目的是什么?
Gis*_*shu 10
基本上,如果给当前方法一个代码块(由调用者调用它),则yield执行传入指定参数的代码块.
[1,2,3,4,5].each { |x| puts x }
Run Code Online (Sandbox Code Playgroud)
现在{ |x| puts x}是x传递给每个方法的代码块(是一个参数)Array.该Array#each实施将遍历本身并打电话给你块与多次x = each_element
pseudocode
def each
#iterate over yourself
yield( current_element )
end
Run Code Online (Sandbox Code Playgroud)
因此结果
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
这*block_args是一种Ruby方式,可以接受未知数量的参数作为数组.调用者可以传入具有不同数量参数的块.
最后让我们看一下块内的收益率.
class MyClass
def print_table(array, &block)
array.each{|x| yield x}
end
end
MyClass.new.print_table( [1,2,3,4,5] ) { |array_element|
10.times{|i| puts "#{i} x #{array_element} = #{i*array_element}" }
puts "-----END OF TABLE----"
}
Run Code Online (Sandbox Code Playgroud)
这里Array#each给出了给出的块的每个元素MyClass#print_table......
这并不意味着什么特别的.这只是收益率和任何其他收益率一样.
def test_method
["a", "b", "c"].map {|i| yield(i) }
end
p test_method {|i| i.upcase }
# => ["A", "B", "C"]
Run Code Online (Sandbox Code Playgroud)
在活动记录的代码片段中,目的是在每次any?调用块时生成.