我的部分代码如下:
class Array
def square!
self.map {|num| num ** 2}
self
end
end
当我打电话时:
[1,2,3].square!
我希望得到 [1,4,9],但我得到的是 [1,2,3]。为什么会这样?当我打电话时:
[1,2,3].map {|num| num ** 2}
在类方法之外,我得到了正确的答案。
最佳答案
你必须使用 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.
class Array
def square!
self.map! {|num| num ** 2}
end
end
[1,2,3].square! #=> [1, 4, 9]
关于arrays - 如何在 Ruby 的 Array 类中对数组的每个元素进行平方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16723386/