Detailed explanation of the iterator IN Ruby and the Ruby Generator

Source: Internet
Author: User

Detailed explanation of the iterator IN Ruby and the Ruby Generator

D guago recently wanted to build a website. In addition, he had long had the idea of learning a dynamic language. Among the programming languages that meet two conditions, Ruby and Python are the most appropriate. Now Ruby on Rails is booming! Therefore, we chose Ruby and learned from scratch.

I saw the Ruby iterator the day before yesterday. For anyone who has only learned Java, C/C ++, this is definitely a bright spot! And it's brilliant: I didn't expect the iterator to be able to play like this. It's so concise, convenient, and especially powerful! Then, Brother D can't wait to write an article to introduce you to the Ruby iterator!

Introduction to iterator

First, let's briefly introduce the iterator.

1. A Ruby iterator is a simple method that can receive code blocks (for example, the each method is an iterator ). Feature: if a method contains yield calls, this method must be an iterator;

2. the iterator method and the block have the following transfer relationship: the block is passed to the iterator method as a special parameter, while the iterator method can pass the parameter value into the block when calling the code block using yield internally;

3. In fact, the iterator function is a callback! The class to which the iterator method belongs is only responsible for traversing the elements to be traversed, and the processing of the elements is implemented through the callback code block;

4. The container objects (such as arrays, ranges, and Hash objects) in Ruby contain two simple iterators: each and collect. Each can be considered as the simplest iterator, which calls blocks for each element of the set. Collect: Pass the elements in the container to a block. After processing in the block, a new array containing the processing result is returned;

Iterator details

The iterators in Ruby can be said to be varied. Next we will give a brief introduction to Ruby iterators from the following aspects: String, number, array, Map, file, and directory.

String iterator

In Java, data of the string type does not have an iterator. Therefore, if you need to "traverse" the string, you need to do some other processing. However, this is in Ruby. The following code demonstrates how:
Copy codeThe Code is as follows:
Str = "abc"
Str. each_byte {| c | printf "> % c", c };#

# The output is as follows: (to distinguish it from the code, D guago artificially adds # In front of the output #.)
# The following output is displayed in the same way.
#> A> B> c

Each_byte is the iterator used in the string to process each byte. Each byte is substituted into block parameter c.

In Ruby, there are not only byte iterators, but also iterators for each row. Example:

Copy codeThe Code is as follows:
Str = "abc \ nefg \ nhijk"
Str. each_line {| l | print l}

# The output is as follows:
# Abc
# Efg
# Hijk

How about it? Isn't it affected by Ruby's concise but powerful iterator ?! The show is still behind, and you can look down.

Digital iterator

In Ruby, "Everything is an object", and even numbers are objects. This is different from Java. Therefore, the word iterator is unknown to the Java programmer. Let's write two examples for a glimpse.

Scenario 1: perform N (for example, 5) operations on a specific code segment. In Java, you need to write a loop, but in Ruby, you only need to call the times method. The Code is as follows:
Copy codeThe Code is as follows:
5. times {print "I love http://www.bkjia.com/\ n"} # It's really that simple

# The output is as follows:
# I love http://www.bkjia.com/
# I love http://www.bkjia.com/
# I love http://www.bkjia.com/
# I love http://www.bkjia.com/
# I love http://www.bkjia.com/

Scenario 2: Calculate the sum of numbers from 1 to 5. This is also very simple:
Copy codeThe Code is as follows:
Sum = 0
(1 .. 5). each {| I | sum + = I}
Print "Sum =" + sum. to_s

If you use the upto function, you can also write as follows:
Copy codeThe Code is as follows:
Sum = 0
1. upto (5) {| x | sum + = x}
Print "Sum =" + sum. to_s

Sometimes, our step is not necessarily 1, it may be 2, such as odd and. In this case, you can use the step function. The Code is as follows:
Copy codeThe Code is as follows:
Sum = 0
1. step (5, 2) do | y | # The second parameter of the step function is step.
Sum + = y
End
Print "Sum =" + sum. to_s

It seems a little far away. Next, let's talk about the array-related iterator.

Array iterator

After seeing the number-related iterator, let's look at the array-related iterator.

First scenario: Facilitate the array and output each element. Directly run the Code:
Copy codeThe Code is as follows:
Ages = ['Ruby ', 'javascript', 'java']
Ages. each_with_index do | lang, I |
Puts "# {I}, I love # {lang }! "
End

# The output is as follows:
#0, I love Ruby!
#1, I love Javascript!
#2, I love Java!

Sometimes, we need to make a selection for the elements of the array, then we can do this:
Copy codeThe Code is as follows:
# Find the value that meets the condition
B = [1, 2, 3]. find_all {| x % 2 = 1}
# The value of B is [1, 3]

Sometimes, we need to delete some values in the array. At this time:
Copy codeThe Code is as follows:
# Iteration and division based on conditions
A = [2, 51,101,256]
A. delete_if {| x> = 100}
# The value of a is [51]

Another example:

Copy codeThe Code is as follows:
# Find the longest string of the longest word
Longest = ["cat", "sheep", "bear"]. inject do | memo, word |
(Memo. length> word. length )? Memo: word
End
Puts longest

# The output is as follows:
# Sheep

Map iterator

In Java, if you use an iterator relative to Map, you must convert Map to a List-type container. However, in Ruby, there is an iterator for Map directly, which is very convenient:

Copy codeThe Code is as follows:
Sum = 0
Outcome = {"book1" => 1000, "book2" => 1000, "book3" => 4000}
Outcome. each {| item, price |
Sum + = price
}
Print "Sum =" + sum. to_s

Even we can:
Copy codeThe Code is as follows:
Sum = 0
Outcome = {"book1" => 1000, "book2" => 1000, "book3" => 4000}
Outcome. each {| pair |
Sum + = pair [1] # Read Value
}
Print "Sum =" + sum. to_s

Note: The above program uses pair [1] to read the Map value. If you want to read the Map key, it is written as pair [0].

If you need to output the Map Key, you can do this:
Copy codeThe Code is as follows:
Outcome = {"book1" => 1000, "book2" => 1000, "book3" => 4000}
Outcome. each_key do | k |
Puts k
End

If you need to output the Map value, you can do this:

Copy codeThe Code is as follows:
Outcome = {"book1" => 1000, "book2" => 1000, "book3" => 4000}
Outcome. each_value do | v |
Puts v
End

File iterator

I really didn't think that Ruby also has an iterator available for files. As follows:
Copy codeThe Code is as follows:
F = File. open ("sample.txt ")
F. each {| line |
Print line
}
F. close

In fact, we can use a code block to perform the same operation:

Copy codeThe Code is as follows:
File. open ("str. rb", "r") do | file |
File. each {| line |
Print line
}
End

You do not need to close the code block manually. This is recommended!

Directory iterator

In many cases, you need to list the files in a directory and set operations on each file. In this case, you also need an iterator. Ruby also considers the following:
Copy codeThe Code is as follows:
Dir. foreach ("c: //") do | file | # modify the file according to your system type.
Puts file
End

# If there are too many outputs, no results will be posted. Run it on your own.

End

From the above introduction, we can see that Java and Ruby are weak in terms of iterators! Of course, D guago has just begun to learn Ruby, and there are some improper or even wrong explanations in the text. He is tired of pointing out that D guago will correct it as soon as possible.


What is the iterator and why does it need the iterator?

Iterator?
Iterator used to traverse every element in the Set

What is the difference between ++ it and it ++ in the iterator map? Will it cause overflow? Details

++ It adds 1z to it for processing.
It ++ is the first processing of it, and Adds 1 more after the end.
For example
Int a = 0, B = 0;
B = a ++; // process it first, that is, B = a, B = 0, then aplus 1, a = 1; the result is: B = 0; a = 1;
Compared with this:
Int a = 0, B = 0;
B = ++ a; // Add 1 first, that is, a = 1. After processing, B = a, B = 1. The result is: B = 1; a = 1;

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.