SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Thursday, May 20, 2010

Destructive effects as danger in ruby

No doubt most of the bang methods we will come across in the core Ruby language
have the bang on them because they’re destructive: they change the object on which
they’re called. Calling upcase on a string gives you a new string consisting of the origi-
nal string in uppercase; but upcase! turns the original string into its own uppercase
equivalent, in place:

>> str = "Hello"
=> "Hello"
>> str.upcase
=> "HELLO"
>> str

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

=> "HELLO"


Examining the original string after converting it to uppercase shows that the uppercase version was a copy; the original string is unchanged B. But the bang operation has changed the content of str itself.

Ruby’s core classes are full of destructive (receiver-changing) bang methods paired with their non-destructive counterparts: sort/sort! for arrays, strip/strip! (strip leading and trailing whitespace) for strings, reverse/reverse! for strings and arrays,and many more. In each case, if you call the non-bang version of the method on the object, you get a new object. If you call the bang version, you operate in-place on the same object to which you sent the message.