开发者

Overriding elements of an array in "each" loop

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

After t开发者_运维百科his operation array a is still [1, 2, 3]. How to convert it into [11, 12, 13]?


Use the collect! method:

a = [1, 2, 3]
a.collect!{ |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.


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}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜