Block are one of the most important and most used features of Ruby. They are very similar to anonymous functions in other languages.
They are very common - here is an example:
[1, 2, 3].each do |n|
puts "#{n}"
end
Just like with methods - they take arguments, performdefined tasks and return a value. In fact, their syntax is very similar to the to the method syntax:
do |arguments|
...
end
Curly braces can be used instead of the do-end syntax:
{ |arguments|
...
}
NB: These 2 ways of definining a block are identical.
Returning value
Just like with methods, a block returns the value of the last statement inside the block.
You get a block, and you get a block
... everyone gets a block!
Every method in Ruby has a hidden block parameter that the method can yield to:
def say_hello_to(name)
puts "Hello #{name}"
yield name
end
say_hello_to("Jenny") { |n| puts "#{n} from the block" }
Hello Jenny Jenny from the block