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

我的部分代码如下:
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}

在课堂方法之外,我得到了正确的答案.

解决方法

你必须使用 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,3].square! #=> [1,9]

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...