数组 – 如何在Ruby中的Array类中对数组的每个元素进行平方?

前端之家收集整理的这篇文章主要介绍了数组 – 如何在Ruby中的Array类中对数组的每个元素进行平方?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的部分代码如下:
  1. class Array
  2. def square!
  3. self.map {|num| num ** 2}
  4. self
  5. end
  6. end

我打电话的时候:

  1. [1,2,3].square!

我希望得到[1,4,9],但我得到[1,3].为什么会这样?我打电话的时候:

  1. [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.

  1. class Array
  2. def square!
  3. self.map! {|num| num ** 2}
  4. end
  5. end
  6.  
  7. [1,3].square! #=> [1,9]

猜你在找的Ruby相关文章