(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