liveBook · Manning

Bang method

As explained in The Well-Grounded Rubyist, Fourth Edition

Bang notation is the exclamation-mark suffix convention in Ruby method names that signals potentially unexpected or otherwise divergent behavior.

In Ruby, `!` can end a method name, but it does not change how Ruby calls or executes the method. It is a convention: a bang method warns that its behavior differs in a potentially surprising way from the method with the same name minus `!`. Most bang methods should have that nonbang partner. section 7.3 section 7.3.2

>> str = "Hello"
=> "Hello"
>> str.upcase
=> "HELLO"
>> str
=> "Hello"         1
>> str.upcase!
=> "HELLO"
>> str
=> "HELLO"           2

Compare `upcase` and `upcase!`: the first returns an uppercase string while leaving `str` alone; the second changes `str` itself. section 7.3.1

The warning is broader than mutation:

  • `sort!`, `strip!`, and `reverse!` change their receivers; their nonbang partners produce new objects. In-place changes can avoid creating extra objects, but other code may depend on the original object staying unchanged. section 7.3.1
  • `exit!` differs from `exit` by skipping finalizers. `sub!` changes its string and returns `nil` when it makes no substitution, unlike `sub`. section 7.3
  • Mutation does not itself call for a bang: `clear` and `replace` change strings without one. Name a method `save!` only if a related `save` exists and the two differ meaningfully. section 8.1.5 section 7.3.2

To inspect the convention, filter a string’s `methods` for names ending in `!`, then check whether each has a nonbang partner. The suffix is not an absolute rule: Builder uses `instruct!` without `instruct` so its own commands remain distinct from method calls that generate XML tags. section 15.2.1 section 13.3.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains the convention through mutation, return values, and exceptions, while deferring a deeper treatment of mutable objects.
Examples
Contrasts `upcase` with `upcase!`, discusses `exit!` and `sub!`, and checks string method names for nonbang partners.
What it assumes
Assumes familiarity with Ruby method calls and strings, but introduces the bang naming convention directly.
What you can do after
Evaluate/understand it by checking a method pair’s effects before choosing it or using a bang in a new name.
How it connects
Connects method naming conventions to object mutation, return values, string transformations, and runtime introspection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.