Ruby Code blocks (called closures in other languages) are definitely one of the coolest features of Ruby and are chunks of code between braces
or between do..end
.
A Ruby block is a way of grouping statements, and may appear only in the source adjacent to a method call.
The code in the block is not executed at the time it is encountered. Instead, Ruby remembers the context in which the block appears (the local variables, the current object, and so on) and then enters the method.
Tip
|
Use braces for single-line blocks and do..end for multi-line blocks and braces syntax has a higher precedence than the do..end syntax.
|
If the method invocation has parameters that are not enclosed in parentheses, the brace form of a block will bind to the last parameter, not to the overall invocation. The do form will bind to the invocation.
Any method can be called with a block as an implicit argument. Inside the method, you can call the block using the yield keyword with a value."
-
Invoke block using
yield
def call_block
puts 'Start of method'
# you can call the block using the yield keyword
yield
yield
puts 'End of method'
end
-
Invoke block using
yield
call_block { puts 'In the block' }
# don't pass block to method
begin
call_block # no block given (LocalJumpError)
rescue
end
-
Inspect block using
block_given?
def try
if block_given? // (1)
yield
else
puts 'no block'
end
end
try # => "no block"
try { puts 'hello' } # => "hello"
-
returns
true
ifyield
would able to execute block in current context
-
Block variables
x = 10
5.times do |x|
puts "x inside the block: #{x}"
end
puts "x outside the block: #{x}"
-
Understanding outer and inner block variables
x = 10 // (1)
5.times do |y|
x = y // (2)
puts "x inside the block: #{x}"
end
puts "x outside the block: #{x}" // (3)
-
This is outer 'x' as it is before block on next line
-
This 'x' is inside block and different than outer 'x'
-
Outer 'x'
Proceed to Array
Go to Table of Content