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 trial

Ruby Ruby Foundations Blocks Working With Blocks

David Bell
David Bell
16,997 Points

Why would I use blocks instead of creating functions or methods?

Maybe this becomes more evident as I continue, but blocks seem to serve the same purpose as functions, in that they are segments of code passed into a method as an argument.

The error handling seems critical to debugging and securing code. But, it seems like all that would work regardless of the block implementation.

So, why use blocks instead of passing methods as an argument?

2 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Yeah, you're correct, basically a block just iterate through each item in the collection and pass it as argument to an anonymous function (function with no name); and yes, since right now you're learning the basics of Ruby from simple examples, you probably don't see the differences of blocks VS defining your own method to iterate through a collection.

Let me say that block is surely the defining feature of Ruby, it lies at the heart of Ruby's raw expressive power. You'll certainly see more examples of how using block makes your code more concise and easier to read, but right now I'm afraid I can't explain too much about the power of blocks without touching on subjects you haven't learned yet.

Let me give you just this one example. Many of the predefined methods in the Enumerable module takes only block as its argument, say, map for example, it traverse through a collection, does some computation to each item, and return a new collection, if you were to define the method your own, it'd be sth like this:

def my_map(arr)
  result = Array.new
  for index in arr
    result << index*3
  end
  result
end

my_map([1,2,3])   #=> [3,6,9]

Nothing wrong with this code, it works; but if you use map instead, and pass a block to it, then

[1,2,3].map {|i| i*3}   #=> [3,6,9]
David Bell
David Bell
16,997 Points

Ah, wow. I see how that example is pretty powerful.

Thanks! I'll stick with it ad keep an open mind to the possibilities.

David Bell
David Bell
16,997 Points

OK, I'm just a few videos into the new Ruby Blocks course and it makes A LOT MORE sense in that course!

Maybe I should wait until Ruby Foundations is completely re done as the Learn Ruby track.