What if you could write one method that does many jobs just by changing a tiny piece of code you pass in?
Why Block parameters in Ruby? - Purpose & Use Cases
Imagine you want to repeat a task several times, but each time you need to do something slightly different with the data. Without block parameters, you might write the same loop again and again, changing bits manually.
This manual way is slow and boring. You risk making mistakes copying and changing code. It's hard to keep track of what changes where, and fixing bugs becomes a headache.
Block parameters let you pass little pieces of code (blocks) that can take inputs and run inside a method. This means you write the loop once, and customize what happens inside by giving it different blocks with parameters. It's clean, flexible, and easy to read.
numbers.each do |n| puts n * 2 end numbers.each do |n| puts n + 3 end
def repeat_action(numbers) numbers.each do |n| yield(n) end end repeat_action(numbers) { |x| puts x * 2 } repeat_action(numbers) { |x| puts x + 3 }
Block parameters let you write flexible methods that can do many different things with the same data, just by changing the block you pass in.
Think about a recipe where you always bake cookies but sometimes add chocolate chips, sometimes nuts. Block parameters let you keep the baking steps the same and just change the extra ingredient easily.
Manual repetition is slow and error-prone.
Block parameters let methods accept custom code with inputs.
This makes your code cleaner, reusable, and easier to change.