# 2.12Ruby语言的迭代器(Iterator)

### 1.times迭代器

``````循环次数.times do
希望循环的处理
end``````
``````7.times do
puts "满地油菜花"
end``````
``````> ruby times.rb

``````5.times do |i|
puts  "第#{i}此的循环。"
end``````
``````> ruby times.rb

### 2.each迭代器

``````对象.each do |块变量|
希望循环的处理
end``````
``````a = [3,2,1]
a = a - 1
a.each do |x|
print x+1
end                           #结果为"4321"``````

### 3.loop迭代器

``````loop do
print "Ruby"
end``````

### 4.upto/downto迭代器

n.times与0.upto(n-1)是等价的。

``1.upto(6) { |x| print x }    #prints "123456"``
``6.upto(1) { |x| print x }    #prints "654321"``

### 5.map迭代器

``````a = [1,2,3,4]
b = a.map { |x| x*x }        # [1,4,9,16]``````

### 6.select/reject迭代器

``````a = [1,2,3,4]
b = a.select { |x| x%2==0 }  # [2,4]
c = a.select { |x| x%2==0 }  # [1,3]``````

### 7.inject迭代器

``````a = [1,2,3,4]
a.inject do |sum,x|
sum + x
end                         # 计算元素的和：10``````
{"ft_lang_label":"__label__zh","ft_lang_prob":0.526425,"math_prob":0.966169,"size":1144,"snap":"2021-43-2021-49","text_gpt3_token_len":788,"char_repetition_ratio":0.120175436,"word_repetition_ratio":0.1056338,"special_character_ratio":0.3688811,"punctuation_ratio":0.17391305,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9893079,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-16T00:03:42Z\",\"WARC-Record-ID\":\"<urn:uuid:022a511f-7981-4e2b-8e41-83940ef8dd92>\",\"Content-Length\":\"46979\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:11b9f255-a66a-47e5-85bb-a29fe82cb8d3>\",\"WARC-Concurrent-To\":\"<urn:uuid:76be470e-aa1d-48c1-8bf5-96dcf20ff730>\",\"WARC-IP-Address\":\"101.34.38.212\",\"WARC-Target-URI\":\"https://www.huoxiaoqiang.com/ruby/rubybasic/1511.html\",\"WARC-Payload-Digest\":\"sha1:LOM5OCOBTODV4VHMHD6R7L3XHHUH454X\",\"WARC-Block-Digest\":\"sha1:KOF3CMZF4CSH32OOQIQMAWCWLSZRBET5\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323583087.95_warc_CC-MAIN-20211015222918-20211016012918-00441.warc.gz\"}"}