Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are bang methods dangerous in Ruby?

I've been re-learning Ruby lately, and this page says that usually a bang method is dangerous, but it doesn't say why. Why are bang methods dangerous?

like image 329
Reggie Avatar asked Nov 15 '25 21:11

Reggie


2 Answers

There are two widespread meanings of "dangerous" in standard library and common gems:

  1. Method mutates the receiver, as opposed to returning a copy of the receiver. Example: Array#map!

  2. Method will raise an exception if its primary function can't be performed. Example: ActiveRecord::Base#save!, ActiveRecord::Base#create!. If, say, an object can't be saved (because it's not valid or whatever), save! will raise an error, while save will return false.

I usually add a third meaning to it in my code:

  1. Method will immediately persist data in the database, instead of just changing some attributes and hoping that later someone will save the object. Example: hypothetical Article#approve!
like image 129
Sergio Tulentsev Avatar answered Nov 17 '25 10:11

Sergio Tulentsev


The page you refer to includes this:

Normally for the built-in classes, dangerous usually (although not always) means this method, unlike its non-bang equivalent, permanently modifies its receiver.

like image 31
theglauber Avatar answered Nov 17 '25 10:11

theglauber