Code Blocks in Ruby
Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a method in one single line or multi lines. Each variant of code block has its cons and pros.
Example of single line block is presented below
[‘a’,’b’,’c’,’d’].each {|item| puts item}
Code block, in the example above, is everything that specified inside curly brackets. Another example shows you code blocks which are longer than one line.
[‘a’,’b’,’c’,’d’].each do |item|
puts “#{item}”
end
Both of these code blocks do the same but single line block is more compact and somewhat easier to read. In addition, curly brackets have precedence over the do… end variant. However, it is easy to run into compile error if curly brackets are not applied properly right after method call. Let’s examine the following line of code.
10.upto(20) {|item| puts item}
We can potentially specify the range in “10.upto 20” form or call to a method with parameters without use of parenthesis. However, if we are to use single line code block right after, we’ll run into compilation error. So, it is always a good idea to use parenthesis in the single line code block.
Code blocks can accept argument which are usually specified at the beginning of the code block enclosed in pipes and separated by comma. Please be aware, you can’t set up default values for these arguments.
Closures are Code Blocks in Ruby in case you may have heard about Closures in the context of Ruby.