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

标签 arrays ruby perfect-square

我的部分代码如下:

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/

相关文章:

arrays - 在线性时间内将未知数量的元素插入动态数组

添加输出文件后 C++ 代码无法正确编译

ruby-on-rails - "rake routes"导致语法错误 : time_zone. rb 循环参数引用 - 现在

检查n个数是否是完全平方数以及如何计算它们的和?

ios - 当元素添加/删除到数组时得到通知

c - 字符指针预增

ruby-on-rails - 约定 : if (! foo) 与除非 (foo)。 while (!foo) vs until (foo)

ruby - 将两个哈希数组合并为一个而不更改 Ruby 中的键值对

c - Perfect Square 功能无法正常使用?