Become a better developer.

A weekly exploration into topics to make you a better Ruby dev.

Our latest issue was about 19 hours ago: Time Off

When Method Names Should Go Out with a Bang

Yesterday I was trying to explain to @eviedently why some methods in Ruby end with an exclamation mark and some don’t.

For example, Rails has two save methods:!

I started to explain that the exclamation mark, or “bang”, means that the method is “destructive.” That means it can change the original object, user in this case.

…Then I realized I wasn’t making any sense.

Both “save” methods cause a change. The real difference is that one returns false when there are validation errors, and one raises an exception.

In fact, Ruby is full of destructive methods like Array#pop and String.insert that don’t end in “!”.

So, if “!” doesn’t indicate destructiveness, what is it for? Matz spelled it out in the Ruby mailing list:

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.

It’s fascinating that it took me so long to question the bang-means-destructive rule, with so much evidence staring me in the face. And I’m not the only one. Search for “ruby method bang” and you’ll see lots of people propagating this myth.

It really makes you wonder what else you’re missing.

Get our weekly email about topics that will make you a better engineer. (Newest: Metaprogramming)