How to square each element of an array in Array class in Ruby?

核能气质少年 提交于 2019-12-05 05:00:27

You have to use Array#map!, not 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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!