Forum: Ruby String substitution?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
023710c8555937142592c1d072d66c7b?d=identicon&s=25 Roberto Rivera (azazel)
on 2007-04-27 23:44
Hello,

Im working on a small rails app that uses a text editor component
(FCKEdit). In certain cases, the editor will add characters to my string
that I need to remove before I show the output.

For example, it will add '\' in front of any '"' or '\' in my document.

I was checking out String.replace and String.gsub, but they both seem to
replace any element that matches the input string.

"hello".gsub(/[aeiou]/, '*')              #=> "h*ll*"

In my particular case, I need it to match the whole string for
substitution.

I worked out this code in order to substitute '\"' for '"' and '\\' for
'\':

<%= text.split('\"').join('"').split("\\\\").join("\\") %>

Im sure there's gotta be some other way to make it work without breaking
it into arrays and rejoining.

Any help will be appreciated.
az
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-04-27 23:56
(Received via mailing list)
On 4/27/07, Roberto Rivera <roberto.rivera@gmail.com> wrote:
>
> "hello".gsub(/[aeiou]/, '*')              #=> "h*ll*"
>
> In my particular case, I need it to match the whole string for
> substitution.
>
> I worked out this code in order to substitute '\"' for '"' and '\\' for
> '\':
>
> <%= text.split('\"').join('"').split("\\\\").join("\\") %>
First of all there is nothing wrong with this(1), I like it a lot,
however as you have asked;)

text.gsub('\"','"').gsub("\\\\","\\")

might indeed be considered a little bit more concise.

Funny how this pattern just matches my previous post in the string
replacement thread.

HTH
Robert
(1) With the exception of a trailing \" or \\"
023710c8555937142592c1d072d66c7b?d=identicon&s=25 Roberto Rivera (azazel)
on 2007-04-28 00:19
Robert Dober wrote:
> On 4/27/07, Roberto Rivera <roberto.rivera@gmail.com> wrote:
>>
>> "hello".gsub(/[aeiou]/, '*')              #=> "h*ll*"
>>
>> In my particular case, I need it to match the whole string for
>> substitution.
>>
>> I worked out this code in order to substitute '\"' for '"' and '\\' for
>> '\':
>>
>> <%= text.split('\"').join('"').split("\\\\").join("\\") %>
> First of all there is nothing wrong with this(1), I like it a lot,
> however as you have asked;)
>
> text.gsub('\"','"').gsub("\\\\","\\")
>
> might indeed be considered a little bit more concise.
>
> Funny how this pattern just matches my previous post in the string
> replacement thread.
>
> HTH
> Robert
> (1) With the exception of a trailing \" or \\"

Indeed, I was trying to get a more concise alternative. Yours is
perfect.
Thanks
This topic is locked and can not be replied to.