Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between downcase and downcase! in Ruby

I am just learning Ruby and I don't quite understand the difference between several Ruby methods with and without a '!' at the end. What's the difference? Why would I use one over the other?

like image 616
Ash Avatar asked Apr 02 '09 10:04

Ash


1 Answers

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.

like image 189
sris Avatar answered Oct 03 '22 02:10

sris