Look Familiar?

Now that you know what a block is, you may notice that you’ve seen them before. Many times. For example, you previously used do..end blocks to iterate over ranges like this:

(1..3).each do |i|
    puts(i)
end

You have also used do..end blocks to iterate over arrays (see for_each2.rb in for Loops):

arr = ['one','two','three','four']
arr.each do |s|
    puts(s)
end

And you have executed a block repeatedly by passing it to the loop method (see 3loops.rb in loop):

i=0
loop {
    puts(arr[i])
    i+=1
    if (i == arr.length) then
        break
    end
}

The previous loop example is notable for two things: It has no list of items (such as an array or a range of values) to iterate over, and it is pretty darn ugly. These two features are not entirely unrelated! The loop method ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.