Methods that end with a “bang” in Ruby are arcane. These are the ones which require a “!” (exclamation mark) at the end of a method.
Consider the example below.
“!” after .capitalize modifies the object for good. The string “Example” will be always capitalized in your program whenever you call the variable string. Easy to understand right? I thought so too until I started bagging anything under the sun that needed changing.
As part of one of the ruby homework, students were asked to change the third letter of all strings in this array:
stuff = [“candy”, :pepper, “wall”, :ball, “wacky”]
Note that the array has both symbols and strings and elements. Thus, the solution should work for an array with different types of objects
My esteemed classmate Chris and I came up with the following piece of code:
The result surprised us. We thought that .collect! would modify the third letter of all string elements in the array stuff for the character “$”, but we were not expecting that the character would substitute entire string. After some discussion, we suspected that the bang was the culprit of our perplexity. Once we removed the exclamation mark, we got this:
A long “ah” followed. We were aware that bang after a method would mutate the object which it was called on, but not to such extent! It went on to replace the entire string when we just wanted to change a particular character index of such string.
The lesson learned was that banging just for the sake of it is dangerous. As with the example shown above, it can bring unexpected consequences. Think of the exclamation mark as in this sign:
Sometimes you are so hyped up that you just desire to bang anything. It seems to be the easier solution to both your problems and the stress that comes with solving them. But banging indiscriminately brings forth unwarranted creations. And these creations can give you more headaches than it would have had if you hadn’t banged in the first place.
When in doubt, don’t bang anything!