In principle, if a block code was provided to the current method (calling when it was called), it yieldtransfers the code in the specified parameters.
[1,2,3,4,5].each { |x| puts x }
Now { |x| puts x}this is a block code ( x- parameter) passed to each method Array. The implementation Array#eachwill iterate over itself and call your block multiple times withx = each_element
pseudocode
def each
yield( current_element )
end
It follows that
1
2
3
4
5
*block_argsis a Ruby method for accepting an unknown number of parameters as an array. The caller can pass in blocks with a different number of arguments.
Finally, let's see what the result is inside the block.
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----"
}
Array#each , MyClass#print_table...