# URI.encode does not encode &=?

**URL:** <https://www.ruby-forum.com/t/uri-encode-does-not-encode/103030>\
**Category:** Rails\
**Created:** [May 1, 2007, 12:18am UTC](https://www.ruby-forum.com/t/uri-encode-does-not-encode/103030 "2007-05-01T00:18:02Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Reynard](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/6bbea6/32.png) [@Reynard](https://www.ruby-forum.com/u/Reynard)\
**Post date:** [May 1, 2007, 12:18am UTC](https://www.ruby-forum.com/t/uri-encode-does-not-encode/103030/1 "2007-05-01T00:18:02Z")

</div>

I’m wondering why URI.encode does not encode &=?  
URI.encode(’&=?’)  
=\> ‘&=?’

Is there alternative that works better? or should I write my own?

-reynard

---

<div class="post-metadata">

**Author:** ![Reynard](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/6bbea6/32.png) [@Reynard](https://www.ruby-forum.com/u/Reynard)\
**Post date:** [May 1, 2007, 5:17am UTC](https://www.ruby-forum.com/t/uri-encode-does-not-encode/103030/2 "2007-05-01T05:17:22Z")

</div>

What’s the second argument supposed to be though?  
should I create a regexp from scratch or use a pre-defined one? the  
documentation is not very clear.

> From googling I found that some people say URI.encode is buggy and  
> suggested to use CGI.escape?  
> seems to work for me.

- reynard

---

<div class="post-metadata">

**Author:** ![Reynard](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/6bbea6/32.png) [@Reynard](https://www.ruby-forum.com/u/Reynard)\
**Post date:** [May 1, 2007, 4:08am UTC](https://www.ruby-forum.com/t/uri-encode-does-not-encode/103030/3 "2007-05-01T04:08:17Z")

</div>

There’s an optional second arg to specify chars to replace:

[http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/classes/URI/Escape.html#M009245](http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/classes/URI/Escape.html#M009245)

b

---

<div class="post-metadata">

**Author:** ![Reynard](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/6bbea6/32.png) [@Reynard](https://www.ruby-forum.com/u/Reynard)\
**Post date:** [May 1, 2007, 6:13am UTC](https://www.ruby-forum.com/t/uri-encode-does-not-encode/103030/4 "2007-05-01T06:13:24Z")

</div>

After I sent that I got curious… I found that the second arg is just a  
regex with the chars to escape… so /[&=?]/ would escape the chars  
you’re worried about.

I also found however, that it _only_ escapes the chars in the regex if  
you provide one… so you’ll have to make sure to escape the stuff that  
would have been escaped.

I also figured out that the REGEXP::UNSAFE constant they mention is  
actually URI::REGEXP::UNSAFE. If you require ‘uri’ in irb and then type  
that, it’ll dump the chars that are in the default regex:

/[^-\_.!~\*’()a-zA-Z\d;/?:@&=+$,[]]/n

And, one more thing: the file that this is defined in should be at  
RUBY\_ROOT/uri/common.rb… and there are a lot of regexes defined in  
there.

b
