The iterator in Ruby detailed _ruby topics

Source: Internet
Author: User
Tags string find ruby on rails


D Guadalcanal recently wanted to do a website, in addition, the old has learned a dynamic language idea, to meet the two conditions of the programming language, Ruby, Python is the most appropriate two languages. Now Ruby on Rails is in the ascendant, shine! So, you've chosen Ruby to start learning from scratch.



The day before yesterday saw Ruby's iterator, for me this has only studied Java, C + + and so on person, definitely is the front of a bright feeling! And is dazzling: did not think the iterator can also play this way, too concise too convenient and particularly powerful! Then, d melon can not wait to write an article to introduce you to introduce the iterator of Ruby!



Introduction to Iterators



Let's briefly introduce the iterator.



1. A ruby iterator is a simple way to receive blocks of code (for example, each method is an iterator). Feature: If a method contains a yield call, the method must be an iterator;



2. The transitive relationship between the iterator method and the block is as follows: The block is passed to the iterator method as a special parameter, and the parameter value can be passed into the block when the code block is invoked by using yield in the iterator method;



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



Container objects in 4.Ruby (such as arrays, range, and hash objects) contain two simple iterators, each and collect. Each can be considered the simplest iterator, which calls blocks on each element of the collection. Collect, the elements in the container are passed to a block, which is processed in the block to return a new array containing the processing result;



Iterator detailed



The iterators in Ruby are all sorts of things, and we'll give you a simple introduction to Ruby's iterators from strings, numbers, arrays, maps, files, directories, and so on.



String iterators



In Java, data of string type does not have an iterator. So, if you need to "traverse" a string, you need to do something else with the string. But it's in Ruby. Next, we'll show you through the code:


 code as follows:

str = "ABC"
Str.each_byte {|c| printf ">%c", C}; #


# The output is as follows: (in order to differentiate with the code, D Guadalcanal in the output before the artificially added #. )
# The output shown below is handled in the same way.
#>a>b>c





Each_byte is the iterator used to process each byte in a string. Each byte will be in block parameter C.



In Ruby, there are not only iterators for bytes, but also iterators for each row. Examples are as follows:





 code as follows:

str = "Abc\nefg\nhijk"
str.each_line{|l| Print L}


# The output is as follows:
#abc
#efg
#hijk





How is it that Ruby's terse but powerful iterator is impressed?! The show is still in the back, then look down.



Digital iterators



In Ruby, "Everything is Object", even numbers are objects. This is not the same as Java. So, for the word iterator, for me this Java program Ape is also unheard of. Let's write two examples with a glimpse of one or two.



The first scenario: an n (for example, 5) operation on a piece of code. In Java, you need to write a loop, but in Ruby you just need to call the Times method. The code is as follows:


code as follows:

5.times {print "I love http://www.jb51.net/\ n"} # It's really that simple


# The output is as follows:
#I Love http://www.jb51.net/
#I Love http://www.jb51.net/
#I Love http://www.jb51.net/
#I Love http://www.jb51.net/
#I Love http://www.jb51.net/





Second scenario: Find the sum of numbers from 1 to 5. This is also particularly simple:


 code 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 this:


 code as follows:

sum = 0
1.upto (5) {|x| sum = x}
Print "sum=" +sum.to_s





Sometimes, our stepping is not necessarily 1, maybe 2, for example, odd number and. In this case, you can use the step function. The code is as follows:

 code as follows:


sum = 0
1.step (5, 2) do |y| # step function The second parameter is stepping.
sum = y
End
Print "sum=" +sum.to_s





It feels a little far away. Next, we'll talk about array-related iterators.



Array iterator



Having seen the number-related iterators, let's look at the array-related iterators.



First scenario: facilitate arrays and output each element. Directly on the code:


 code as follows:

languages = [' Ruby ', ' Javascript ', ' Java ']
Languages.each_with_index do |lang, i|
Puts "#{i}, I love #{lang}!"
End


#输出如下:
#0, I Love ruby!
#1, I Love javascript!
#2, I Love java!





Sometimes we need to make a selection of the elements of an array, and then we can do this:


 code as follows:

# Find the values that match the criteria
b = [1,2,3].find_all{|x| x 2 = 1}
The value of # B is [1,3]





Sometimes, we need to delete some values from the array. Then:


 code as follows:

# iteration and delete according to condition
A = [51, 101, 256]
a.delete_if {|x| x >= 100}
The value of # A is [51]





One more example:





 code as follows:

# finding the longest string find the longest word
longest = ["Cat", "sheep", "Bear"].inject do |memo,word|
(Memo.length > Word.length)? Memo:word
End
Puts longest


#输出如下:
#sheep





Map iterator



In Java, if a relative map uses iterators, the map must be converted to a container of type list. However, in Ruby, there is a direct iterator for the map, which is good and convenient:




 code 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 do this:


 code as follows:

sum = 0
Outcome = {"Book1" =>1000, "Book2" =>1000, "Book3" =>4000}
outcome.each{|pair|
Sum + = pair[1] # Read value
}
Print "sum=" +sum.to_s





Here is a note: The above program uses PAIR[1] to read the value of the map, written as Pair[0 if you want to read the map's key.



If you need to output the key of the map, you can do this:


 code as follows:

Outcome = {"Book1" =>1000, "Book2" =>1000, "Book3" =>4000}
Outcome.each_key do |k|
Puts K
End





If you need to output the value of a map, you can do this:





code as follows:

Outcome = {"Book1" =>1000, "Book2" =>1000, "Book3" =>4000}
Outcome.each_value do |v|
Puts V
End





File iterators



It is really not thought that for files, Ruby also has iterators available. As follows:


 code as follows:

f = File.Open ("Sample.txt")
f.each{|line|
Print Line
}
F.close





In fact, we can use code blocks to do the same thing:





 code as follows:

File.Open ("Str.rb", "R") do |file|
file.each{|line|
Print Line
}
End





With code blocks, manual close is not required. This recommendation!



Directory iterator



Most of the time, we need to list the files in a directory, set up the operation of each file, and then need an iterator. Ruby also takes into account the following:


 code as follows:

Dir.foreach ("c://") do |file| # Please make the appropriate changes according to your system type.
Puts file
End


#输出太多, the results are not posted. You can run it by yourself and see





End



As you can see from the above introduction, Java and Ruby, compared to the iterator is simply a weak burst! Of course, D is just beginning to learn Ruby, the text has improper or even explain the wrong place, please point out that D will be corrected as soon as possible.


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.