Ruby Ruby Blocks Blocks Practice Build a Monster Class: Part 1

Nicolas Filzi
Nicolas Filzi
18,021 Points

Can't see a concrete point behind Ruby Blocks, any eye-opening example for me folks? :)

What could I use it for when building websites for instance?

1 Answer

David Clausen
David Clausen
11,403 Points

I agree with your sense they seem pointless. A method can replace them usually. I think that is an example of using simplified examples to demonstrate it.

But anytime in ruby you use a block like a while loop

i = 0
while i  < 5 do
  i += 1
  puts "HI"
end

this will print:
HI HI HI HI HI => nil

right?

Guess what? We can create that while function ourselves since Ruby exposes blocks.

def myloop(iterations)
  i = 0
  while i < iterations do
    yield
    i += 1
  end
end


myloop(5) do
  puts "HI"
end

I've created a loop that loops exactly the number of times i give it. There are better methods to do this, but the fact is you can create your own way of handling blocks. You can have people basically create anonymous function that get one off handed to your method.

You can define your own each (iterators), loops ect. Ruby uses these blocks for a lot of it tricks. 5.times{puts "HI"}, ruby each methods, while loops, untils. All they've done is expose it so you can utilize it as a tool for solving problems.

This guys goes over blocks and shows some good examples http://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes

There isn't to say one perfect way of doing it, but you may find that maintainability or readability in different solutions, it seems Ruby doesn't limit its tools for you do to that. If Ruby utilizes it in its language, you can too.