On Banging

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!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s