Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 2

Blocks and iterators

Block
It is a chunk of code enclosed between either braces or the keywords do and end.
some_array.each {|value| puts value * 3}
sum = 0
other_array.each do |value|
sum += value #sum = sum + value
puts value / sum
end
Block is like a the body of an anonymous method. It can take parameters in | |. The
body of a block is not executed when Ruby first sees it. It is saved to be called later.
Logic: Blocks can appear only immediately after the invocation of some method. If
the method takes parameters, the block appears after these parameters. Block is
one extra parameter passed to the method.
sum = 0
[1, 2, 3, 4].each do |value|
square = value * value
sum += square #sum = sum + square
end
puts sum #30

square = Shape.new(sides: 4)
sum = 0
[1, 2, 3, 4].each do |value|
square = value*value
sum += square
end
puts sum
square.draw #Error. Variable square was overridden in the block.
To solve this problem, Ruby has a couple of answers.
(1) Parameters are always local to a block even if they have the same name as
locals in the surrounding scope.
value = some shape
[1, 2].each {|value| puts value}
puts value
#1
#2
#some shape
(2) You can define a block-local variables by putting them after a semicolon in the
blocks parameter list.
square=some shape
sum = 0
[1, 2, 3, 4].each do |value ; square|
square = value * value
sum += square
end
puts sum
puts square
#30
#some shape

Iterator
A Ruby iterator is simply a method that can invoke a block of code.
A block may appear only in the source adjacent to a method call and that the code in
the block is not executed at the time it is encountered.

You might also like