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
