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.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…