Creating my own method

P

Paul Sholtz

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
Ruby?

For instance, if I have:

def f(s)
s = "new string"
end

and then I call:

s = "test string"
f(s)
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"
end

and then when I call:

s = "test string"
f!(s)
puts s

the output will be "new string"?
 
J

John Feminella

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

Yep. Just do this:

=3D=3D=3D=3D begin snippet =3D=3D=3D=3D
def newify!(s)
s.gsub!(/test/, "new")
end
=3D=3D=3D=3D end snippet =3D=3D=3D=3D

Now you'll get:

=3D=3D=3D=3D begin snippet =3D=3D=3D=3D
s =3D "here's a test string"
newify!(s)
puts s
# =3D> "here's a new string"
=3D=3D=3D=3D end snippet =3D=3D=3D=3D

~ jf
 
A

Adam Prescott

[Note: parts of this message were removed to make it a legal post.]

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

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

Also, note that ! at the end of a method name does not always mean "modifies
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, String#replace
itself has no ! -- !.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top