Specifying Blocks with Method Calls
Methods may be called with blocks of code specified that will be called from within the method.
method_call{[|[variable[,variable...]]|]code}method_calldo [|[variable[,variable...]]|]codeend
Calls a method with blocks specified. The code in the block is executed after a value is passed from the method to the block and assigned to the variable (the block’s argument) enclosed between ||.
A block introduces its own scope for
new local variables. The local variables that appear first in the
block are local to that block. The scope introduced by a block can
refer local variables of outer scope; on the other hand, the scope
introduced by class, module and
def statement can’t refer outer local
variables.
The form {...} has a higher precedence than
do ... end.
The following:
identifier1 identifier2 {|varizable| code}actually means:
identifier1(identifier2 {|variable| code})On the other hand:
identifier1 identifier2 do |variable| code end
actually means:
identifier1(identifier2) do |variable| code end
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access