PHP Urlencode equivalent in Ruby

By | June 6, 2011

If you are finding a way to encode urls in ruby then here is a quick tip -

Short Answer: You could use the URI class or the CGI class.

We have CGI.escape and URI.escape, but they have some slight differences. I have tried to show the differences in IRB as follows -

$ irb
irb(main):001:0> str = 'hello world'
=> "hello world"
irb(main):002:0> require 'uri'
=> true
irb(main):003:0> URI.escape(str)
=> "hello%20world"
irb(main):004:0> require 'cgi'
=> true
irb(main):005:0> CGI.escape(str)
=> "hello+world"
irb(main):006:0> url = 'åäö'
=> "åäö"
irb(main):007:0> URI.escape(url)
=> ""
irb(main):008:0> CGI.escape(url)
=> ""

So i hope you can see the difference now and can choose the one you need.


Last Updated On : 6th June 2011

Leave a Reply

Your email address will not be published. Required fields are marked *