July 2011
Intermediate to advanced
400 pages
8h 46m
English
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)
endYou 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)
endAnd 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 ...
Read now
Unlock full access