[英]What does Ruby block return to?
Good day.再会。 I've tried writing this code in ruby
我试过用 ruby 编写这段代码
x = [1, 2, 3, 4, 5]
x.each do |a|
a + 1
end
When I type this in irb, I don't understand why does it return => [1, 2, 3, 4, 5]当我在 irb 中输入这个时,我不明白为什么它返回 => [1, 2, 3, 4, 5]
I thought it would return => [2, 3, 4, 5, 6] # because of a + 1我以为它会返回 => [2, 3, 4, 5, 6] # 因为 a + 1
each
yields the array's elements to the given block (one after another) without modifying the array.each
将数组的元素生成到给定的块(一个接一个)而不修改数组。 At the end, it returns the array, as mentioned in the docs:最后,它返回数组,如文档中所述:
[...] passes each successive array element to the block;
[...] 将每个连续的数组元素传递给块; returns
self
回归
self
You are probably looking for map
, which works similar to each
but instead of returning self
, it ...您可能正在寻找
map
,它的工作原理与each
类似,但不是返回self
,而是......
[...] returns a new Array whose elements are the return values from the block
[...] 返回一个新数组,其元素是块的返回值
Example:例子:
x = [1, 2, 3, 4, 5]
x.map { |a| a + 1 }
#=> [2, 3, 4, 5, 6]
Note that it returns a new array without actually modifying x
.请注意,它返回一个新数组,而没有实际修改
x
。 There's also map!
还有
map!
(with !
) which does modify the receiver. (使用
!
)它确实修改了接收器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.