Ruby Iterator usage _ruby topics

Source: Internet
Author: User
The iterator was not invented by Ruby. It is widely used in all kinds of object-oriented languages. In Lisp, it's just not called that. However, the concept of iterators is not familiar to many people, so we will do a more detailed description here.

You know, the verb iterate means to do the same thing many times, so iterator is something that will do the same thing many times.

When we write code, we need loops in various environments. In C, we use for or while.

Char *str;
for (str = "ABCDEFG"; *str!= '; str++ ') {
/* Process a character here * *
}


C for (...) Syntax provides an abstract way of writing loops, but testing whether *STR is a null character requires the programmer to understand the details of the inner structure of the string. This makes C look like a low-level (low-level) language. More advanced languages are implemented through their more resilient iterator support. Consider the following SH Command-line scripting:

#!/bin/sh
For i in *. [CH]; Todo
# ... here would is something to does for each file
Done


All C source and header files in the current directory are processed, and the command-line shell picks up the file name and handles the details. I think it's a higher level than C, don't you think?

But there's more to consider: while a language can provide an iterator for a built-in data type, it's disappointing that we still need to go back and use the lower-level loop language to implement iterations of our own data types. In the face of object programming, users often define data types one after the other, So this is a very serious problem.

Therefore, all OOP languages contain a certain iterator mechanism. Some languages provide a special class for this purpose; Ruby allows us to define the iterator directly.

Ruby's String type has a number of useful iterators:

Ruby> "abc". each_byte{|c| printf "<%c>", C}; print "\ n"
<a><b><c>
Nil


Each_byte is an iterator for each character in a string. Each string is replaced by a local variable C. This can be translated into code like C ...

Ruby> s= "abc"; i=0
0
Ruby> while I<s.length
| printf "<%c>", s[i]; I+=1
| End print "\ n"
<a><b><c>
Nil


... However, the Each_byte iterator is conceptually simpler, and should work even if the String class changes suddenly. One of the benefits of using iterators is that you can still be robust in such a change, and it's really a feature of good code in general. (OK, please have a little patience, we'll talk about what class is right away)

Another iterator for string is each_line.

Ruby> "a\nb\nc\n". each_line{|l| Print L}
A

C
Nil


Using iterators, this will easily replace most of C's programming effects (find line breaks, generate substrings, and so on)

The For statement that appears earlier implements the iteration functionality through each iterator. Each of the string and each_line work the same, let's rewrite the above example with a for:

Ruby> for L in "a\nb\nc\n"
| Print L
| End
A

C
Nil


We can use the Retry Process Control statement to join the iteration loop, which executes the iteration of the current loop from the beginning.

Ruby> c=0
0
Ruby> for I in 0..4
| Print I
| if i = = 2 and c = 0
| c = 1
| print "\ n"
| Retry
| End
| End print "\ n"
012
01234
Nil


Yield sometimes appears in the definition of an iterator. Yield moves process Control to the code domain that is passed to the iterator (this will introduce more detail in the Procedure Object section). The following example defines a repeat iterator that executes multiple code fields depending on the parameter's settings.

ruby> def repeat (num)
| While num > 0
| Yield
| num-= 1
| End
| End
Nil
Ruby> Repeat (3) {print "foo\n"}
Foo
Foo
Foo
Nil


With retry, we can define an iterator with the same role as while, although it is too slow in practical applications.

Ruby> def while (cond)
| return if not cond
| Yield
| Retry
| End
Nil
Ruby> i=0; while (i<3) {print i; I+=1}
012 Nil


Do you understand what an iterator is? There are some limitations, but you can write your own iterator; in fact, when you define a new data type, it is often convenient to define a suitable iterator for it. It seems that the above example is not very useful. After we understand the class, We can discuss the more practical iterators.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.