I often use one liners to search and replace within strings:
"my string is a string".gsub(/(st.)/, 'big \1')
=> "my big string is a big string"

Note two important syntax items:
1. put parentheses around the item to be referenced later...
2. Parenthetically captured items are accessible via \1 reference
within the replacement string.



On Jul 29, 11:46 am, Nik So <niks...@gmail.com> wrote:
> I did originally want to overwrite the existing string, but the more I think
> about it, using a new string is better.
>
> Thanks Colin!
>
> Nik
>
>
>
>
>
> On Wed, Jul 29, 2009 at 12:17 PM, Colin Law <clan...@googlemail.com> wrote:
>
> > 2009/7/29 Nik So <niks...@gmail.com>:
> > > I see, do you mean that, instead of over-writing my existing string, I
> > > should get a new string which consists of
>
> > > new_str = $` + $'
>
> > I thought you wanted chevrons and the y also. You can overwrite the
> > existing string if you want to
>
> > str = 'abcydef'
> > str =~ /y/
> > str = "<#{$`}>y<#{$'}>"
> > or something similar.
>
> > Colin
>
> > > ?
>
> > > Best,
>
> > > On Wed, Jul 29, 2009 at 6:18 AM, Colin Law <clan...@googlemail.com>
> > wrote:
>
> > >> 2009/7/29 Nik <niks...@gmail.com>:
>
> > >> > Hey guys, thanks for your help!
>
> > >> > I found out about $`, $& and $', as well as $1 - $9. But here is still
> > >> > the problem. They do *find* the "abc" or "xxx" in front of "y"
>
> > >> > But I *cannot* act on them, I can only read them.
> > >> > I am saying, I can't do something like
>
> > >> > $` = " <#{$`}>"
>
> > >> new_string =  " <#{$`}>y"
>
> > >> Colin
>
> > >> > these variables seem to be read-only
>
> > >> > Any ideas?
>
> > >> > Thanks again!
> > >> > On Jul 28, 1:05 pm, coreypurcell <corey.purc...@gmail.com> wrote:
> > >> >> str = "vvvyxxx"
>
> > >> >> str =~ /y/
>
> > >> >> $`
> > >> >>  => "vvv"
>
> > >> >> $'
> > >> >>  => "xxx"
>
> > >> >> Like spacecow said. It's $ Backtick
>
> > > --
> > > Nik So
>
> --
> Nik So
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to