(13) iterators

Source: Internet
Author: User

(1) Iterator Times,each,sort

Iterators are special loops that make it easier to traverse, sort, or otherwise manipulate

4. times{
Print "Hello"
}

4. times{|N|
PrintN
}
Puts"----"
a=[7,8,9]
a. each{
|N|
PutsN
}
Puts"----"
Hashes={"a"="One","B"=222}
Hashes . each{
| key,value|
Puts "#{key}:#{ value}"
}

Here is the sort iterator for sorting

a=[1,2,3,4]
a. sort{|a,b|
b a #表示取出a在前b在后, put back when B is in front a behind, implement the reverse order
}
Puts a
puts "-------"
a =a . sort{| a , b |
b a
}
puts a #sort迭代器也要接收覆盖原来的才能看到改变

(2) Custom iterators

In fact, iterators are just functions, and we call iterators just as we call functions, and we can write iterators ourselves:

attr_accessor :title,:author
attr_accessor与它后面的第一个冒号要用空格隔开

class Book
  attr_accessor :title,:author

defInitialize(title,author)
@author=author
@title=Title
End
End

Class Booklist
def
Initialize ()
@book_list = Array .new
end

def
add ( book )
@book_list .push ( book )
End

def length
@book_list .length
end


#可以用方括号去获取当前是哪一本书
def[](N)
@book_list[N]
End
#可以用方括号修改对应下标书籍
def[]=(N, Book)
@book_list[N]=Book
End
#删除一本书
defDelete( Book)
@book_list. Delete (book)
End
#自定义一个迭代器, the title of the circulating output book
def Each_title
@book_list . each{
| Book |
yield (booktitle) #yield有专门章节讲解, or one of the more important keywords
}
End
End


Temp=Booklist. New
a= Book. New ("001","first book")
b= book .new ( "002" , "Second book" )
temp .add ( a )
Span style= "color: #003c5a;" > temp .add ( b )
# title corresponds to Book.title
.each_title{| title |
puts title
}

(13) iterators

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.