RFS: Bang (!) vs No Bang Method Calls - 018

This was one of the great mysteries of ruby when I initialy got started. Reading through the documentation one will find 2 variations of the same method call one variation would look something like .map and the other would look like .map!

What does the ! (bang) signify, and why do we have it? Let's find out

Method Calls without Bang

We'll use the map method call on an array as an example

numbers = [1, 3, 6, 9]squared = numbers.map do |x|  x * xendp squared[1, 9, 36, 81]p numbers[1, 3, 6, 9]

Notice that the value of numbers remain un-changed and the value of squared is the result of the .map operation.

Method Calls with Bang (!)

Let's try the .map! call on numbers

numbers.map! do |x|  x * xendp numbers[1, 9, 36, 81]

We can see that the .map! method has mutated the state of numbers

This is the difference between the bang variation and the no bang variation of a method call. In ruby we use the ! when we want to let the user of our method know that something destructive might happen. In this case we lost the original value of the array because it was replaced by the result of the method call.