10

I'm learning Ruby and I've seen that an exclamation mark at the end of a method name by convention means that the method modifies self in some way. Why doesn't then Array#delete end with an exclamation mark, like slice! does, since delete deletes an element from self? Am I missing something fundamental?

Boris B.
  • 4,933
  • 1
  • 28
  • 59
  • My guess is because `#delete` can do only delete so there is no need to flag it. Something like `#upper_case` can either be assigned to a newly created object or overwrite the original object at the determination of the use. – ScottJShea Feb 28 '12 at 20:35
  • Yes, but #delete with no flag could also return a clone minus the specified element (That's what I expected given the absence of a flag) :) – Boris B. Feb 28 '12 at 20:45
  • possible duplicate of [Why are exclamation marks used in Ruby methods?](http://stackoverflow.com/questions/612189/why-are-exclamation-marks-used-in-ruby-methods) – Peter O. Feb 28 '12 at 21:34

2 Answers2

14

To quote Matz (Ruby's chief engineer):

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 Array#delete doesn't have a less-dangerous counterpart, there is no need for the exclamation.

sgtFloyd
  • 997
  • 1
  • 9
  • 18
4

The "bang" methods don't mean that it modifies the receiver. It is an indication of a method that is a more dangerous version of an existing method. See David A. Black's description of the difference, and the response to a request to change Ruby 2.0.

This is a very common misconception. Note the very highly-voted wrong answer here.

Community
  • 1
  • 1
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101