Ruby: Block basics

A Block in Ruby is equivalent to a Lambda or Anonymous (un-named) Function in other languages. It starts with do, ends with end, and its parameters are defined between | |:

# statement-1
do |country_name|
  puts "Hello #{country_name}!"
end

Note that a Block looks a LOT like a Method, except that a Method is defined with def(instead of do), is given a name, and encloses parameters in ( ) instead of| | .

You can also define a Block using curly braces instead of do-end:

# statement-2
{ |country_name|
  puts "Hello #{country_name}!"
}

You can pass a Block as an argument to a Method (think of it as a callback). To demonstrate this, we will define a Method named hello_world.

# statement-3
def hello_world(world_name)
  puts "Hello #{world_name}!"
  yield("USA") if block_given?
end
# statement-4
hello_world("Earth") {|country_name| puts "Hello #{country_name}!" }

In statement-4 above, there are basically 2 arguments passed to the Method hello_world:
1) the String "Earth" and
2) the Block {|country_name| puts "Hello ${country_name}!" }.
Even though the Block is not inside the parentheses with "Earth", the Block is still treated as an argument.

Basically, the yield keyword in the Method hello_world is replaced with the contents of the Block. The Block is then passed the argument "USA".

If you had 2 yield keywords in the Method hello_world, the Block would be executed 2 times.