This chapter demonstrates about the Ruby Blocks which ruby defines several methods user can put any number of statements and following are the concepts covered in this chapter.
About Ruby Blocks
Blocks and Methods
About Ruby Blocks
Description
Ruby defines several methods where user can put number of statements and user can call those methods similarly ruby have a concept called block. User can assign any name to the block which consist of chunks of code and the code is always enclosed with in the braces ({}). Block is always invoked with the same name of the block and user can invoke the block with yield statement The syntax below demonstrates the block.
[ruby]
block_name{
statement1
statement2
..........
}
[/ruby]
If user want to invoke the block then user need to use the yield statement. the code below demonstrates the yield statement as shown below.
[ruby]
def test
puts "You are in the splessons method"
yield
puts "You are again back to the splessons method"
yield
end
test {puts "You are in the splessons block"}
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.
Blocks and Methods
Description
In Ruby Blocks and methods are associated with each other normally block can be invoked by yield statement from a method which have the same name of the block but if the last argument preceded by & then user need to pass block to method and block will be assign to the last parameter. In which cases both * and & are present with in the argument list, & will come later. the code below demonstrates the block methods as shown.
[ruby]
def test(&block)
block.call
end
test { puts "Hello World!"}
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.
Every ruby blocks have block of code to be run as the file is being loaded and after the program it has to finish The code below demonstrates begin and ending blocks as shown.
[ruby]
BEGIN {
# BEGIN block code
puts "BEGIN code block"
}
END {
# END block code
puts "END code block"
}
# MAIN block code
puts "MAIN code block"
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.
Summary
Key Points
Ruby consist of beginning and ending blocks.
Ruby Blocks and methods are associated with each other.