覆盖“each”中数组的元素环形

发布于 2024-11-06 03:22:45 字数 140 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浪推晚风 2024-11-13 03:22:45

使用 collect! 方法:

a = [1, 2, 3]
a.collect!{ |x| x + 10 }

Use the collect! method:

a = [1, 2, 3]
a.collect!{ |x| x + 10 }
装迷糊 2024-11-13 03:22:45

有两类通用的解决方案:

命令式对象变异代码

a.map! { |x| x + 10 }

几乎函数式 解决方案

a = a.map { |x| x + 10 }

这两种技术都有自己的位置。

There are two general classes of solutions:

Imperative object-mutating code

a.map! { |x| x + 10 }

An almost functional solution

a = a.map { |x| x + 10 }

Both techniques have their place.

分分钟 2024-11-13 03:22:45

我自己喜欢“地图”这个别名。它的字符较少。

与您所做的相比,这些方法的差异有两倍。一是您必须使用修改初始数组的方法(通常是 bang 方法,或者名称以 ! (map!、collect!、...) 结尾的方法。第二件事是.each 是通常用于遍历数组以使用各个元素的方法,Map 或 Collect 方法返回一个包含块每次迭代的返回值的

数组

a = [1,2,3]
b = []
a.each do |x| 
   b << x+10
end

。 dmarko 演示的映射或收集方法或如下所示:

a = [1,2,3]
a = a.map {|x| x+10}

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:

a = [1,2,3]
b = []
a.each do |x| 
   b << x+10
end

or you could use the map or collect method as demonstrated by dmarko or as here:

a = [1,2,3]
a = a.map {|x| x+10}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文