# RegEx stuff

**URL:** <https://www.ruby-forum.com/t/regex-stuff/143195>\
**Category:** Ruby\
**Created:** [July 16, 2008, 7:12am UTC](https://www.ruby-forum.com/t/regex-stuff/143195 "2008-07-16T07:12:58Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jturney](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e99b99/32.png) [@jturney](https://www.ruby-forum.com/u/jturney)\
**Post date:** [July 16, 2008, 7:12am UTC](https://www.ruby-forum.com/t/regex-stuff/143195/1 "2008-07-16T07:12:58Z")

</div>

a = [[“a^b^^”], [“c&def”]]  
b= []

a.to\_s.each\_byte { |byte| (b.push(byte.chr) if !b.include?(byte.chr)) if  
byte.chr.match(/\W+/) }

b.each do |c|  
a=a.to\_s.gsub(c, “\#{c}”).to\_a  
end

p a

=\> [“a\^b\^\^c&def”]

How come the & does not get subbed with ‘\&’ ??

I’m basically trying to substitute any special character with  
‘\#{special\_character}’

THANKS!

---

<div class="post-metadata">

**Author:** ![jturney](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e99b99/32.png) [@jturney](https://www.ruby-forum.com/u/jturney)\
**Post date:** [July 16, 2008, 9:00am UTC](https://www.ruby-forum.com/t/regex-stuff/143195/2 "2008-07-16T09:00:41Z")

</div>

On Jul 16, 1:08 pm, Justin To [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> p a  
> Posted viahttp://www.ruby-forum.com/.  
> try  
> a=a.to\_s.gsub(c, “\\#{c}”).to\_a

“\” will present as ''  
‘&’ will present as ‘&’

---

<div class="post-metadata">

**Author:** ![jturney](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e99b99/32.png) [@jturney](https://www.ruby-forum.com/u/jturney)\
**Post date:** [July 16, 2008, 10:20am UTC](https://www.ruby-forum.com/t/regex-stuff/143195/3 "2008-07-16T10:20:54Z")

</div>

From: Justin To [[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)]

# =\> [“a\^b\^\^c&def”]

# How come the & does not get subbed with ‘\&’ ??

# I’m basically trying to substitute any special character with

# ‘\#{special\_character}’

i’m a block fan, so,

irb(main):048:0\> b.each do |c|  
irb(main):049:1\* a=a.to\_s.gsub(c){“\#{c}”}.to\_a  
irb(main):050:1\> end  
=\> [“^”, “&”]

irb(main):052:0\> a  
=\> [“a\^b\^\^c\&def”]

using block form of gsub wont give you problems on escaping the escape…

kind regards -botp

---

<div class="post-metadata">

**Author:** ![jturney](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e99b99/32.png) [@jturney](https://www.ruby-forum.com/u/jturney)\
**Post date:** [July 16, 2008, 8:42pm UTC](https://www.ruby-forum.com/t/regex-stuff/143195/4 "2008-07-16T20:42:46Z")

</div>

Great thanks!
