我的部分代码如下:
- class Array
- def square!
- self.map {|num| num ** 2}
- self
- end
- end
我打电话的时候:
- [1,2,3].square!
我希望得到[1,4,9],但我得到[1,3].为什么会这样?我打电话的时候:
- [1,3].map {|num| num ** 2}
在课堂方法之外,我得到了正确的答案.
解决方法
你必须使用
@L_403_0@,而不是
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,3].square! #=> [1,9]