Difference Between downcase and downcase! in Ruby Difference Between downcase and downcase! in Ruby ruby ruby

Difference Between downcase and downcase! in Ruby


Methods with an exclamation mark at the end are often called bang-methods. A bang method doesn't necessarily modify its receiver as well as there is no guarantee that methods without a exclamation mark doesn't.

It's all very well explained in this blog post. To quote the post:

The ! in method names that end with ! means, “This method is dangerous”—or, more precisely, this method is the “dangerous” version of an otherwise equivalent method, with the same name minus the !. “Danger” is relative; the ! doesn’t mean anything at all unless the method name it’s in corresponds to a similar but bang-less method name.

and

The ! does not mean “This method changes its receiver.” A lot of “dangerous” methods do change their receivers. But some don’t. I repeat: ! does not mean that the method changes its receiver.


The non-bang downcase() method simply returns a new object representing you string downcased.

The bang version modifies your string itself.

my_text = "MY TEXT"my_new_text = my_text.downcaseputs my_new_text # will print out "my text"puts my_text     # will print out "MY TEXT" - the non-bang method doesn't touch itmy_text.downcase!puts my_text # will print out "my text". The bang version has modified the object you're calling the method on