Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Blocks Ruby Blocks Calling Blocks

Why do we need blocks in real world programming?

I think I didn't get well blocks and also can't figure out how it will be useful on real world programming?

Can you serve me additional resources for blocks ?

3 Answers

Hey Batuhan, According to http://radar.oreilly.com, "Used properly, they can reduce repetition and even make coding less error-prone." You can check some examples in the following link: http://radar.oreilly.com/2014/02/why-ruby-blocks-exist.html

David Clausen
David Clausen
11,403 Points

I am still confused about these too. The example you linked to could be achieved with methods to replace the def do_something_with_every_item block with methods that do the same thing.

Maybe I haven't seen enough examples, thought maybe since you found that you'd have another one up your sleeve! If you do thanks!

Roland Cedo
Roland Cedo
21,261 Points

I was just struggling with that same question. This article over at codeacademy made sense to me:

tl;dr: We may want to use blocks if we have a function that should behave slightly differently every time we call it. It allows you to modify how your function works on the fly when you call it. (this might not be the most eloquent answer - but checkout the article, it helped me alot)


Megan Babbitt
Megan Babbitt
7,826 Points

Blocks can be pretty confusing to understand. Blocks are kind of like anonymous chunks of code that can be passed as arguments to a method. You will find yourself using them a lot in Ruby and in testing. Here is a simple example of a block that I used while creating seeds for some posts.

5.times do
     title:  Faker::Lorem.sentence,
     body:   Faker::Lorem.paragraph
 posts = Post.all

These are a few good resources on explaining them that can do a better job than I can!