Modifying Receivers and Yielding New Objects

You may recall from Chapter 4 that I made the distinction between methods that modify their receiver and those that do not. (Remember that a receiver is the object that “owns” the method.) In most cases, Ruby methods do not modify the receiver object. However, some methods, such as those ending with !, do modify their receiver.

The str_reverse.rb sample program should help clarify this. This shows that when you use the reverse method, for example, no change is made to the receiver object (that is, an object such as str1). But when you use the reverse! method, a change is made to the object (its letters are reversed). Even so, no new object is created: str1 is the same object before and after the reverse! ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.