ruby 如何在Ruby中的Array类中对数组的每个元素进行平方?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16723386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to square each element of an array in Array class in Ruby?
提问by mrdziuban
Part of my code is as follows:
我的部分代码如下:
class Array
def square!
self.map {|num| num ** 2}
self
end
end
When I call:
当我打电话时:
[1,2,3].square!
I expect to get [1,4,9], but instead I get [1,2,3]. Why is this the case? When I call:
我希望得到 [1,4,9],但我得到的是 [1,2,3]。为什么会这样?当我打电话时:
[1,2,3].map {|num| num ** 2}
outside of the class method, I get the correct answer.
在课堂方法之外,我得到了正确的答案。
回答by Arup Rakshit
You have to use Array#map!, not Array#map.
您必须使用Array#map!,而不是Array#map。
Array#map-> Invokes the given block once for each element of self.Creates a new array containing the values returned by the block.
Array#map!-> Invokes the given block once for each element of self, replacing the element with the value returned by the block.
Array#map->为 self 的每个元素调用给定块一次。创建一个包含块返回值的新数组。
Array#map!->为 self 的每个元素调用给定块一次,用块返回的值替换该元素。
class Array
def square!
self.map! {|num| num ** 2}
end
end
[1,2,3].square! #=> [1, 4, 9]

