String replace

  • Follow


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
-- 
Posted via http://www.ruby-forum.com/.

0
Reply shandybleu (37) 8/31/2009 4:36:29 PM

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
-- 
Posted via http://www.ruby-forum.com/.

0
Reply shandybleu (37) 8/31/2009 4:42:52 PM


On Tue, 1 Sep 2009 01:42:52 +0900
Shandy Nantz <shandybleu@yahoo.com> wrote:

> @freeform = @freeform.sub(/\[W_FAX\]/, "555-555-5555")

Also consider:

> @freeform.sub!(/\[W_FAX\]/, "555-555-5555")

With "sub!", you can change the variable in-place.


-- 
http://spiralofhope.com


0
Reply spiralofhope (13) 8/31/2009 4:53:12 PM

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

2009/8/31 Shandy Nantz <shandybleu@yahoo.com>

> 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.

--
James Coglan
http://jcoglan.com

0
Reply jcoglan (199) 8/31/2009 4:54:27 PM

3 Replies
41 Views

(page loaded in 0.195 seconds)


Reply: