Skip to content

Grokking Ruby’s Blocks

So… everything I’ve read about Ruby’s blocks seems too esoteric to me… here’s what it boils down to in my mind. See if it helps you…

def myMethod(id)
num = Model.find(id).number_of_items
yield
end

called like:

myMethod(id) { |val| val*2 }

is equivalent to:

def myMethod(id)
num = Model.find(id).number_of_items
num * 2
end

Blocks provide a simple way to change the way a method works by in-lining the code in the block (between the { and the }). If I wanted `myMethod` to triple the number_of_items value (retrieved from a database, maybe?), I could call it thusly:

myMethod(1) { |val| val*3 }

How might this be useful? Let’s say you wanted to retrieve a bunch of rows from a database based on an input value (x), but you needed to format the display differently at different times.

Write your method to take a block, pass the values into the block (that’s what the `|val|` is about, and manipulate within the block!

That’s the way my mind sees it. Maybe it’ll clarify blocks for other someone else, too?

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*