11

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 I get [1,2,3]. Why is this the case? When I call:

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

outside of the class method, I get the correct answer.

Cœur
  • 37,241
  • 25
  • 195
  • 267
mrdziuban
  • 749
  • 3
  • 11
  • 23
  • Any reason (performance?) for destroying the original array (statement/imperative) instead of returning a new one (expression/functional)? – tokland May 23 '13 at 22:32
  • You use `map` to create an array of squares, and then just throw it away and return `self`. – RocketR Mar 21 '15 at 17:56

1 Answers1

19

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]
Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317