Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBatuhan Ozgur Ozdemir
4,658 PointsWhy 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
Francisco Cunha
3,017 PointsHey 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
Roland Cedo
21,261 PointsI 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)
https://www.codecademy.com/forum_questions/51c72e759c4e9d410501df42
Megan Babbitt
7,826 PointsBlocks 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
Post.create!(
title: Faker::Lorem.sentence,
body: Faker::Lorem.paragraph
)
end
posts = Post.all
These are a few good resources on explaining them that can do a better job than I can!
http://www.eriktrautman.com/posts/ruby-explained-blocks-procs-and-lambdas-aka-closures
http://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes
David Clausen
11,403 PointsDavid Clausen
11,403 PointsI 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!