Destructive Methods with No Bang (!)

Throughout my first few months of learning Ruby, I’ve been consistently reminded that we should always exercise caution when using Ruby’s built-in methods that have a name that ends with a bang character (!). These methods permanently modify their callers and could wreak havoc within your code if you aren’t careful.

But before we thank Ruby creator Matz for making these destructive methods easy to spot with the bang (!), we must be aware that for every method with a bang, there seems to be a destructive method without a bang .

For instance,

arr = [100, 200, 400, 600]
=> ["bears", "bears", "bears", "bears"]
=> ["bears", "bears", "bears", "bears"]

So why the inconsistency?

Matz clarifies the intention of the bang(!) with this statement made here:

“The bang (!) does not mean “destructive” nor lack of it mean non-destructive either. The bang sign means “the bang version is more dangerous than its non-bang counterpart; handle with care”. Since Ruby has a lot of “destructive” methods, if bang signs follow your opinion, every Ruby program would be full of bangs, thus ugly.”

The key to understanding why some destructive methods have a bang and others do not is

“the bang version is more dangerous than its non-bang counterpart”

Destructive methods with a bang typically have a twin non-destructive form such as the String methods upcase vs. upcase!. Alternatively, destructive methods without bangs do not have a non-destructive counterpart.

So how is a new programmer to know if a method is destructive or not? The best way to know is to fire up your IRB and test out the method to see its effect. Through consistent practice, we can work on memorizing which methods permanently change their callers.

To make the Rubyist’s life (mainly my life as a novice) a bit easier, here is a list of destructive methods with no bang.

Happy Coding!