def any?
if block_given?
method_missing(:any?) { |*block_args| yield(*block_args) }
else
!empty?
end
end
In this code from ActiveRecord, what is the purpose of a yield statement that exists within a block?
def any?
if block_given?
method_missing(:any?) { |*block_args| yield(*block_args) }
else
!empty?
end
end
In this code from ActiveRecord, what is the purpose of a yield statement that exists within a block?
Basically if the current method has been given a code-block (by the caller, when it was invoked), the
yield
executes the code block passing in the specified parameters.Now
{ |x| puts x}
is the code-block (x
is a parameter) passed to the each method ofArray
. TheArray#each
implementation would iterate over itself and call your block multiple times withx = each_element
Hence it results
The
*block_args
is a Ruby way to accept an unknown number of parameters as an array. The caller can pass in blocks with different number of arguments.Finally let's see what yield within a block does.
Here
Array#each
yields each element to the block given toMyClass#print_table
...This helped me understand:
yield
is a way to insert blocks into a method you already wrote, which means "execute something here". For instance,Without parameter
What if you want to execute some unknown block between those two
p
?The result would be
You can have as many
yield
s in a method as you like.With parameter
What if you want to execute some unknown block on the string
"Execute something on me!"
?The result would be
It does not mean anything special. It's just a yield like any other yield.
In the code snippet from active record, the purpose is to yield every time the block of
any?
is called.