Ruby Blocks
Ruby Blocks
The Ruby blocks syntax and example.
Blocks syntax
block_name{
-- Ruby code
}
--or
do
-- Ruby code
end
Blocks example
def test_block
puts "Method A"
yield
puts "Method B"
yield 123
puts "Method C"
yield "abc"
end
test_block {|x|puts "The block #{x}"}
Output
Method A
The block
Method B
The block 123
Method C
The block abc
Method with block example
def test_method
yield puts "Block 1"
end
test_method{}
Output
Block 1