这个问题在 Ruby 的文档中有多处涉及,但对于您的使用最易理解的是在数组文档中关于
each
的部分。
each { |item| block } → ary
each → Enumerator
Calls the given block once for each element in self, passing that element as a parameter. Returns the array itself.
If no block is given, an Enumerator is returned.
a = [ "a", "b", "c" ]
a.each {|x| print x, " -- " }
produces:
a -- b -- c --
请注意,它说“
返回数组本身”。
将其与
map
进行比较:
map { |item| block } → new_ary
map → Enumerator
Invokes the given block once for each element of self.
Creates a new array containing the values returned by the block.
See also Enumerable#collect.
If no block is given, an Enumerator is returned instead.
a = [ "a", "b", "c", "d" ]
a.collect { |x| x + "!" } #=> ["a!", "b!", "c!", "d!"]
a.map.with_index { |x, i| x * i } #=> ["", "b", "cc", "ddd"]
a #=> ["a", "b", "c", "d"]
注意,它说:“
创建一个新数组,其中包含块返回的值。”
以下示例应有助于了解上述内容:
foo = [1,2,3]
foo.each { |i| puts i + 1 }
foo.map { |i| i + 1 }
其中# =>
是块的返回值,# >>
是从puts
中捕获的STDOUT。
了解这些后,当您想要显示数组中的元素或提取和重用这些元素作为参数或构建内容时,请使用each
。当您想将数组元素更改为其他内容时,请使用map
。
.each
的返回值仍然是原始的可枚举对象(在这两行之后可以看到它)。 - Sergio Tulentsev