n00b string replace

T

theistian

Hi I'm triying to substitute any ocurrences of ' in a string by \'

Here's a bit of testing I made in irb which wtf's me:

irb(main):002:0> st = "un ' monton ' de ' apostrofes '"
=> "un ' monton ' de ' apostrofes '"
irb(main):003:0> sst = st.gsub(/'/,"\'")
=> "un ' monton ' de ' apostrofes '"

ok substitute ' by ' :p I don't know why interpeter interpret \' as
' when in a double-quoted string contex but I'm a newbie so sure I'm
wrong

irb(main):004:0> sst = st.gsub(/'/,"\\'")
=> "un monton ' de ' apostrofes ' monton de ' apostrofes ' de
apostrofes ' apostrofes "
irb(main):005:0> sst = st.gsub(/'/,"\\\'")
=> "un monton ' de ' apostrofes ' monton de ' apostrofes ' de
apostrofes ' apostrofes "

This seems to be substitute ' by "rest of string from ocurrence"
regardless of scape chars

Totally dazzed and desperate I tried with another backslash.... who
cares ... and get this

irb(main):006:0> sst = st.gsub(/'/,"\\\\'")
=> "un \\' monton \\' de \\' apostrofes \\'"

How do I get "un \' monton \' de \' apostrofes \'" from "un ' monton '
de ' apostrofes '"? using regex?

Thanks
 
J

Jon Evans

Hi,

How do I get "un \' monton \' de \' apostrofes \'" from "un ' monton '
de ' apostrofes '"? using regex?

Like this:
=> "un \\' monton \\' de \\' apostrofes \\'"

It just displays with \\ in there because it needs to escape the \
itself when displaying it. Any manipulations you need to do on the
actual string object will only see a single '\' character rather than
a double.
s = "'" => "'"
s.gsub!(/'/, "\\\\'") => "\\'"
s.length => 2
s[0].chr => "\\"
s[1].chr
=> "'"

Jon
 

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

Similar Threads

Chatbot 0
=== is not a symmetric operator? 4
extending ruby - handling errors 10
Set class and repetetive elements 6
string decrement 0
Time + time.local 1
what's wrong with this picture? 7
Where's A? 2

Staff online

Members online

Forum statistics

Threads
474,206
Messages
2,571,068
Members
47,674
Latest member
scazeho

Latest Threads

Top