程式扎記: [Ruby 教學] 表示式 : Expression (Iterators)

標籤

2010年9月12日 星期日

[Ruby 教學] 表示式 : Expression (Iterators)

Iterators 

If you read the beginning of the previous section, you might have been discouraged. ``Ruby has pretty primitive built-in looping constructs,'' it said. Don't despair, gentle reader, for there's good news. Ruby doesn't need any sophisticated built-in loops, because all the fun stuff is implemented using Ruby iterators. 

For example, Ruby doesn't have a ``for'' loop---at least not the kind you'd find in C, C++, and Java. Instead, Ruby uses methods defined in various built-in classes to provide equivalent, but less error-prone, functionality. 

Let's look at some examples.
  1. 3.times do  
  2.   print "Ho! "  
  3. end  

produces:
Ho! Ho! Ho!


It's easy to avoid fencepost and off-by-1 errors; this loop will execute three times, period. In addition to times, integers can loop over specific ranges by calling downto, upto, and step. For instance, a traditional ``for'' loop that runs from 0 to 9 (something like i=0; i < 10; i++) is written as follows.
  1. 0.upto(9do |x|  
  2.   print x, " "  
  3. end  

produces:
0 1 2 3 4 5 6 7 8 9


A loop from 0 to 12 by 3 can be written as follows.
  1. 0.step(123) {|x| print x, " " }  

produces:
0 3 6 9 12

Similarly, iterating over arrays and other containers is made easy using their each method.
  1. 11235 ].each {|val| print val, " " }  

produces:
1 1 2 3 5

And once a class supports each, the additional methods in the Enumerable module (documented beginning on page 403 and summarized on pages 102--103) become available. For example, the File class provides an each method, which returns each line of a file in turn. Using the grep method in Enumerable, we could iterate over only those lines that meet a certain condition.
  1. File.open("ordinal").grep /d$/ do |line|  
  2.   print line  
  3. end  

produces: 
second
third

Last, and probably least, is the most basic loop of all. Ruby provides a built-in iterator called loop.
  1. loop {  
  2.   # block ...  
  3. }  

The loop iterator calls the associated block forever (or at least until you break out of the loop, but you'll have to read ahead to find out how to do that).

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!