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).

2 則留言:

  1. It was very nice article and it is very useful to Testing tools learners.We also provide Ruby on Rails Online Training

    回覆刪除
    回覆
    1. Thanks for the feedback and useful link to learn Ruby.
      Have a good day!

      刪除

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...