String replace

S

Shandy Nantz

I wondering if there is a string replace function.

I have a string that looks something like:

2YP/P:[CTYCODE]B/[W_PHONE]/F/[W_FAX]/R/[H_PHONE]

and what I am looking to do is to replace the [W_PHONE], for example,
with 555-555-5555. What I have right now in terms of code is something
like:

if /\[W_PHONE\]/ =~ 2YP/P:[CTYCODE]B/[W_PHONE]/F/[W_FAX]/R/[H_PHONE]
@var = "555-555-5555
end

which works but it builds a new string, which is fine, but the above
string could be constructed any number of ways - with another variable
string to replace on, or with one missing, etc. What I would really like
to do is replace the string in-place of the one that I am searching for.
Is there a built in ruby function to do this or can someone gets me some
pointers about writing one myself? Thanks,

-S
 
S

Shandy Nantz

I got it: @freeform = @freeform.sub(/\[W_FAX\]/, "555-555-5555"). I
guess that's what I get for not reading a little further in my Ruby
book.

-S
 
J

James Coglan

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

2009/8/31 Shandy Nantz said:
I got it: @freeform = @freeform.sub(/\[W_FAX\]/, "555-555-5555"). I
guess that's what I get for not reading a little further in my Ruby
book.


You might also want String#gsub -- #sub only replaces the first match, #gsub
("global substitute") replaces all matches.
 

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

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,459
Latest member
Vida00R129

Latest Threads

Top