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

Part of my code is as follows:

class Array def square! self.map {|num| num ** 2} self end end 

When i call:

 [1,2,3].square! 

I expect to get [1,4,9], but instead get [1,2,3]. Why is this so? When i call:

 [1,2,3].map {|num| num ** 2} 

outside the class method, I get the correct answer.

+6
source share
1 answer

You must use Array#map! , not Array#map .

Array#map β†’ Calls this block once for each element self.Creates a new array containing the values ​​returned by the block.

Array#map! β†’ Calls this block once for each self element, 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] 
+10
source

Source: https://habr.com/ru/post/945724/


All Articles