liveBook · Manning

Destructive method

As explained in The Well-Grounded Rubyist, Fourth Edition

Destructive behavior is behavior that changes the state of the receiver object rather than producing an unchanged receiver.

A destructive method permanently changes the state of its receiver instead of returning a changed copy. Ruby commonly pairs destructive methods with nondestructive alternatives. section 7.3.1

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

Compare str.upcase, which returns a new uppercase string while preserving str, with str.upcase!, which changes str in place. section 7.3.1

Recognize destructive behavior through these contrasts:

  • Choose the nondestructive form when later code may rely on the original object; choose the destructive form when changing that object is intentional. section 7.3.1
  • Expect pairs such as sort/sort!, strip/strip!, and reverse/reverse!; the non-bang method produces a new object, while the bang method operates on the receiver. section 7.3.1
  • Do not treat ! as a synonym for destructive: bang methods signal potentially dangerous behavior, and some destructive methods, such as clear and push, have no bang. section 7.3.2
  • Balance allocation costs against aliasing risks: new objects can consume resources during large-file processing, while in-place changes can affect other users of the receiver. section 7.3.1

Uppercasing names without changing stored data

For each name in an array, assign name.upcase to capped and use capped for printed output. The original name remains available for later processing; using name.upcase! would alter it in place. section 7.3.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains copying versus in-place mutation, naming conventions, resource tradeoffs, and shared-object risks without detailing implementation internals.
Examples
Uses upcase/upcase!, sort/sort!, strip/strip!, reverse/reverse!, String#clear, Array#push, and uppercase name processing.
What you can do after
Apply destructive and nondestructive methods deliberately while anticipating effects on shared objects and resource usage.
How it connects
Connects destructive methods with bang methods, receivers, object identity, mutation, aliases, and nondestructive methods.

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.