Josh R. answered 01/18/21
Full-Stack Ruby Developer
Hey there!, The bang (!) at the end of a ruby method usually means one of two things. In both cases the bang lets you know what kind of method you're dealing with. For example, if we have an array:
The output printed here will be the original array value, completely unchanged, [1,2,3].
Whereas the output from these statements will still be the original array variable, but it will point to a new value, [2,4,6]. Effectively, using .map! mutates the original value. So what did the first .map do?
Well, it turns out it does the exact same thing, minus one detail. The .map method still passes each value in the original array to the block. The values are transformed and a new array is returned. In the first example, we never captured that value, it's just executed as the second statement and we never do anything with it.
Using .map! means we don't have to reassign the output to a new variable. Our original variable now points to the new, mutated, value. However, that also means our original value is lost, so be careful.
Other methods that contain ! may mean that the operation of this method is altered somehow. I cant say with 100% certainty that this applies in all cases, but most methods that have a ! in them have a counterpart that does not. This decision is obviously up to the creator of the library you're using. A classic example in ActiveRecord is the .save method. The .save method has a .save! counterpart and the .save! counterpart just means that if there is an issue saving the record, it will raise an exception. Useful for debugging.
Hope this helps!