liveBook · Manning

Nonbang method

As explained in The Well-Grounded Rubyist, Fourth Edition

A nondestructive method is a method that leaves its receiver unchanged and returns a new object containing the result.

A nonbang method leaves its receiver unchanged and returns a new object containing the result. In Ruby’s conventional method pairs, it provides the safer alternative to a bang method, which may modify the receiver in place. section 7.3.1 section 7.3

Copy versus in-place change

str = "Hello" str.upcase # => "HELLO" str # => "Hello" str.upcase! # => "HELLO" str # => "HELLO" The nonbang call produces an uppercase copy; the bang call changes str itself. section 7.3.1

Common pairs include sort/sort! for arrays, strip/strip! for strings, and reverse/reverse! for strings and arrays. Choose the nonbang form when later code must still see the original object. section 7.3.1

Use nonbang methods with two trade-offs in mind:

  • Preserve shared data when other parts of the program depend on the receiver remaining unchanged. section 7.3.1
  • Accept the cost of creating result objects; repeated processing of large data sets can increase memory and processing demands. section 7.3.1
  • Treat the exclamation point as a convention rather than a language mechanism: Ruby executes bang methods normally, and not every bang method changes its receiver. section 7.3 section 7.3.2
>> str = "Hello"
=> "Hello"
>> str.upcase
=> "HELLO"
>> str
=> "Hello"         1
>> str.upcase!
=> "HELLO"
>> str
=> "HELLO"           2

Compare a nonbang call and its bang counterpart interactively to observe whether the receiver retains its original value. section 7.3.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains receiver changes, returned objects, resource trade-offs, and naming conventions without descending into object-mutation internals.
Examples
Illustrates upcase/upcase!, sort/sort!, strip/strip!, reverse/reverse!, and nonmutating name processing.
What you can do after
Apply it via Ruby method pairs to preserve shared objects or deliberately accept new-object allocation.
How it connects
Connects nonbang methods to bang methods, receivers, mutable objects, and method-naming conventions.

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.