The do Keyword in Ruby

Nurudeen Ibrahim Feb 09, 2022
  1. Use the do Keyword to Define an Argument in Ruby
  2. Use the each_with_index Method to Accept a Block of Multiple Arguments in Ruby
The do Keyword in Ruby

The do keyword comes into play when defining an argument for a multi-line Ruby block. Ruby blocks are anonymous functions that are enclosed in a do-end statement or curly braces{}.

Usually, they are enclosed in a do-end statement if the block spans through multiple lines and {} if it’s a single line block.

Use the do Keyword to Define an Argument in Ruby

The following are common examples of blocks in Ruby and how do is used to define their arguments.

[1, 2, 3].each do |n|
  puts n
end

Output:

1
2
3

As shown in the example above, each is an example of Ruby methods that accepts a block. Other examples include map, collect, select, reject, each_with_index, etc.

Use the each_with_index Method to Accept a Block of Multiple Arguments in Ruby

Some of these methods accept a block of multiple arguments, usually an iterated value and its index. One good example is the each_with_index method, which can use below.

[1, 2, 3].each_with_index do |n, i|
  puts "Index: #{i}, Value: #{n}"
end

Output:

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3

Related Article - Ruby Keyword