The begin
block is a control structure that groups together multiple statements.
begin
a = 7
b = 6
a * b
end
A begin
block will return the value of the last statement in the block. The following example will return 3
.
begin
1
2
3
end
The begin
block is useful for conditional assignment using the ||=
operator where multiple statements may be required to return a result.
circumference ||=
begin
radius = 7
tau = Math::PI * 2
tau * radius
end
It can also be combined with other block structures such as rescue
, ensure
, while
, if
, unless
, etc to provide greater control of program flow.
Begin
blocks are not code blocks, like { ... }
or do ... end
; they cannot be passed to functions.