Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between URI.escape and URI.encode in Ruby?

Tags:

ruby

I'm trying to figure out a difference between a URI.escape and URI.encode in Ruby.

Neither is doing what I want them to, which is to completely encode an URL.

For example I want http://my.web.com to be http%3A%2F%2Fmy%2Eweb%2Ecom

like image 894
BlackHatSamurai Avatar asked Nov 27 '12 22:11

BlackHatSamurai


People also ask

What does URI escape do?

URI::escape is good for escaping a url which was not escaped properly. For example some websites output wrong/unescaped url in their anchor tag. If your program use these urls to fetch more resources, OpenURI will complain that the urls are invalid.

How do I encode a URL in Ruby?

If you need to encode query strings then CGI. escape method is probably what you're looking for. CGI. escape follows the CGI/HTML forms spec and returns a string like application/x-www-form-urlencoded requests, which requires spaces to be escaped to + and encode most special characters.


1 Answers

There is no difference. In Ruby 1.9.3 encode is simply an alias for escape.

[Edit] Note that those methods allow an "unsafe" descriptor of characters to encode:

URI.encode('http://my.web.com', /\W/) # => "http%3A%2F%2Fmy%2Eweb%2Ecom"

Thanks @muistooshort! =)

like image 155
maerics Avatar answered Sep 21 '22 14:09

maerics