0
0
Rubyprogramming~10 mins

Block syntax (do..end and curly braces) in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Block syntax (do..end and curly braces)
Start
Call method with block
Ruby reads block syntax
If do..end
Execute block lines
If curly braces
Execute block lines
<--- Back to method
Method finishes
End
<--- Back to method
Ruby methods can take blocks written with do..end or curly braces. Ruby reads the block, executes its lines, then returns to the method.
Execution Sample
Ruby
3.times do
  puts "Hi"
end
This code runs the block 3 times, printing "Hi" each time.
Execution Table
StepActionBlock SyntaxOutput
1Call 3.times with blockdo..end
2Execute block iteration 1do..endHi
3Execute block iteration 2do..endHi
4Execute block iteration 3do..endHi
5Finish methoddo..end
💡 All 3 iterations done, method ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
Key Moments - 2 Insights
Why can we use both do..end and curly braces for blocks?
Both are block delimiters in Ruby. do..end is often used for multi-line blocks, curly braces for single-line, but both work the same as shown in the execution_table.
Does the block run immediately when passed?
No, the method (like times) controls when the block runs. The execution_table shows the method calls the block 3 times.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed at Step 3?
A"Hi"
B"Hello"
CNothing
DError
💡 Hint
Check the Output column at Step 3 in the execution_table
At which step does the method finish running the block?
AStep 2
BStep 5
CStep 4
DStep 1
💡 Hint
Look at the Action column and Output column in the execution_table
If we replace do..end with curly braces, what changes in the output?
ACode breaks with error
BOutput changes to "Hello"
COutput stays the same
DBlock runs only once
💡 Hint
Refer to the concept_flow and key_moments about block syntax equivalence
Concept Snapshot
Ruby blocks can be written with do..end or curly braces.
Both delimit a block of code passed to methods.
Blocks run when the method calls them.
do..end is preferred for multi-line blocks.
Curly braces often used for single-line blocks.
Output depends on block code executed inside method.
Full Transcript
This lesson shows how Ruby uses blocks with two syntaxes: do..end and curly braces. When a method like times is called with a block, Ruby reads the block code inside the delimiters. The method controls how many times the block runs. For example, 3.times do puts "Hi" end runs the block 3 times, printing "Hi" each time. Both do..end and curly braces work the same way, with do..end often used for multi-line blocks and curly braces for single-line blocks. The execution table traces each step: calling the method, running the block 3 times, and finishing. This visual helps beginners see how blocks execute step-by-step.