How to use Ruby iterator

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]; Do
# ... here would is something to do the 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

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.