Creating my own "bang" method

Suppose I have a string, say s = “test string” … the difference between
s.gsub and s.gsub! is whether or not the method modifies the object
itself. That is, s.gsub simply returns a new string w/ the appropriate
modifications, while s.gsub!(/t/,“T”) will change s to a new value, to
wit, “TesT sTring”…

My question is, is there a way that I can create my own “!” methods in

For instance, if I have:

def f(s)
s = “new string”

and then I call:

s = “test string”
puts s

the output is still “test string”…

Is there a way that I can write a method f! so that:

def f!(s)
s = “new string”

and then when I call:

s = “test string”
puts s

the output will be “new string”?

Is there a way that I can write a method f! so that:

Yep. Just do this:

==== begin snippet ====
def newify!(s)
s.gsub!(/test/, “new”)
==== end snippet ====

Now you’ll get:

==== begin snippet ====
s = “here’s a test string”
puts s

=> “here’s a new string”

==== end snippet ====

~ jf

John F.
Principal Consultant, BitsBuilder
SO: User John Feminella - Stack Overflow

You can have ! at the end of your methods, so your f! is a valid method

To replace the contents of the string, instead of creating a new
look at String#replace.

Also, note that ! at the end of a method name does not always mean
the receiver,” it is, in general, a convention meaning “something odd is
happening here.” You can have !-methods without a corresponding !-less
method, and !-less methods can modify the receiver. In fact,
itself has no ! – !.