English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
简单来说:迭代(iterate)指的是重复做相同的事,所以迭代器(iterator)就是用来重复多次相同的事。
迭代器是集合支持的方法。存储一组数据成员的对象称为集合。在 Ruby 中,数组(Array)和哈希(Hash)可以称之为集合。
迭代器返回集合的所有元素,一个接着一个。在这里我们将讨论两种迭代器,each 和 collect。
each 迭代器返回数组或哈希的所有元素。
collection.each do |variable| code end
为集合中的每个元素执行 code。在这里,集合可以是数组或哈希。
#!/usr/bin/ruby ary = [1,2,3,4,5] ary.each do |i| puts i end
The output of the above examples is as follows:
1 2 3 4 5
each 迭代器始终与一个块关联。它向块返回数组的每个值,一个接着一个。值被存储在变量 i 中,然后显示在屏幕上。
collect The iterator returns all elements of the collection.
collection = collection.collect
collect method does not always need to be associated with a block.collect method returns the entire collection, regardless of whether it is an array or a hash.
#!/usr/bin/ruby a = [1,2,3,4,5] b = Array.new b = a.collect{ |x|x } puts b
The output of the above examples is as follows:
1 2 3 4 5
Note:collect method is not the correct way to copy between arrays. There is another called clone method, used to copy an array to another array.
When you want to perform some operation on each value to obtain a new array, you usually use the collect method. For example, the following code will generate an array whose values are the 10 times.
#!/usr/bin/ruby a = [1,2,3,4,5] b = a.collect{|x| 10*x} puts b
The output of the above examples is as follows:
10 20 30 40 50