覆盖“each”中数组的元素环形
a = [1, 2, 3]
a.each do |x| x+=10 end
执行此操作后,数组 a 仍然是[1, 2, 3]
。如何将其转换为[11,12,13]
?
a = [1, 2, 3]
a.each do |x| x+=10 end
After this operation array a is still [1, 2, 3]
. How to convert it into [11, 12, 13]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
collect!
方法:Use the
collect!
method:有两类通用的解决方案:
命令式对象变异代码
几乎函数式 解决方案
这两种技术都有自己的位置。
There are two general classes of solutions:
Imperative object-mutating code
An almost functional solution
Both techniques have their place.
我自己喜欢“地图”这个别名。它的字符较少。
与您所做的相比,这些方法的差异有两倍。一是您必须使用修改初始数组的方法(通常是 bang 方法,或者名称以 ! (map!、collect!、...) 结尾的方法。第二件事是.each 是通常用于遍历数组以使用各个元素的方法,Map 或 Collect 方法返回一个包含块每次迭代的返回值的
数组
。 dmarko 演示的映射或收集方法或如下所示:
I like the aliased name "map" myself. It has less characters.
The difference with these methods as compared to what you've done is two fold. One is that you have to use a method that modifies the initial array (typically these are the bang methods, or the methods which have a name ending in a ! (map!, collect!, ...) The second thing is that a.each is the method typically used for just going through the array to use the individual elements. Map or Collect methods return an array containing a return from each iteration of the block.
Hence, you could have done the following:
or you could use the map or collect method as demonstrated by dmarko or as here: