Ruby 简明教程
Ruby - Iterators
迭代器只不过是集合支持的方法。存储一组数据成员的对象称为集合。在 Ruby 中,数组和哈希可以称为集合。
Iterators are nothing but methods supported by collections. Objects that store a group of data members are called collections. In Ruby, arrays and hashes can be termed collections.
迭代器依次返回集合的所有元素。这里我们将讨论两个迭代器,each 和 collect。让我们详细了解一下它们。
Iterators return all the elements of a collection, one after the other. We will be discussing two iterators here, each and collect. Let’s look at these in detail.
Ruby each Iterator
each 迭代器返回数组或哈希的所有元素。
The each iterator returns all the elements of an array or a hash.
Syntax
collection.each do |variable|
code
end
为集合中的每个元素执行代码。此处,集合可以是一个数组或一个 ruby 哈希。
Executes code for each element in collection. Here, collection could be an array or a ruby hash.
Example
#!/usr/bin/ruby
ary = [1,2,3,4,5]
ary.each do |i|
puts i
end
这会产生以下结果 −
This will produce the following result −
1
2
3
4
5
你总是将 each 迭代器与一个块关联起来。它一次向块返回数组的每个值。该值存储在变量 i 中,然后显示在屏幕上。
You always associate the each iterator with a block. It returns each value of the array, one by one, to the block. The value is stored in the variable i and then displayed on the screen.
Ruby collect Iterator
collect 迭代器返回集合的所有元素。
The collect iterator returns all the elements of a collection.
Syntax
collection = collection.collect
collect 方法不一定总是与一个块相关联。collect 方法返回整个集合,无论它是一个数组还是哈希。
The collect method need not always be associated with a block. The collect method returns the entire collection, regardless of whether it is an array or a hash.
Example
#!/usr/bin/ruby
a = [1,2,3,4,5]
b = Array.new
b = a.collect
puts b
这会产生以下结果 −
This will produce the following result −
1
2
3
4
5
NOTE − collect 方法不是在数组之间进行复制的正确方法。还有另一种称为 clone 的方法,应该使用该方法将一个数组复制到另一个数组中。
NOTE − The collect method is not the right way to do copying between arrays. There is another method called a clone, which should be used to copy one array into another array.
通常在你希望使用每个值来获取新数组时使用 collect 方法。例如,此代码生成包含 a 中每个值的 10 倍的数组 b。
You normally use the collect method when you want to do something with each of the values to get the new array. For example, this code produces an array b containing 10 times each value in a.
#!/usr/bin/ruby
a = [1,2,3,4,5]
b = a.collect{|x| 10*x}
puts b
这会产生以下结果 −
This will produce the following result −
10
20
30
40
50