Ruby Language Control Flow begin, end

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any Ruby Language Question?