0
0
Rubyprogramming~3 mins

Why Block syntax (do..end and curly braces) in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could tell Ruby to do the same thing many times with just a tiny piece of code?

The Scenario

Imagine you want to repeat a task several times or perform an action on each item in a list by writing the same code again and again.

For example, printing each name in a list by typing a separate print statement for each one.

The Problem

This manual way is slow and boring. It's easy to make mistakes like forgetting one item or typing the wrong thing.

Also, if the list changes, you have to rewrite many lines, which wastes time and causes errors.

The Solution

Block syntax lets you write the repeated action just once and tell Ruby to run it for each item automatically.

You wrap the code in do..end or curly braces { }, and Ruby handles the rest.

Before vs After
Before
puts 'Name: Alice'
puts 'Name: Bob'
puts 'Name: Carol'
After
['Alice', 'Bob', 'Carol'].each do |name|
  puts "Name: #{name}"
end
What It Enables

You can easily repeat actions on many items without extra typing, making your code shorter, clearer, and less error-prone.

Real Life Example

Think about sending a thank-you message to every person who attended your party. Instead of writing each message separately, you write one message and use a block to send it to everyone.

Key Takeaways

Manual repetition is slow and error-prone.

Block syntax wraps repeated code neatly for automatic execution.

Using do..end or { } makes code shorter and easier to maintain.