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 is part of the Kernel class, which is “automatically” available to your programs. Because it has no “end value,” it will execute the block forever unless you explicitly break out of it using the break keyword. Usually there are more elegant ways to perform this kind of iteration—by iterating over a sequence of values with a finite range.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.226.66