PHP Urlencode equivalent in Ruby

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 = 'http://example.com/åäö'
=> "http://example.com/åäö"
irb(main):007:0> URI.escape(url)
=> "http://example.com/%C3%A5%C3%A4%C3%B6"
irb(main):008:0> CGI.escape(url)
=> "http%3A%2F%2Fexample.com%2F%C3%A5%C3%A4%C3%B6"

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

Cheers!







Last Updated On : 6th June 2011

Subscribe to get updates delivered to your inbox

Leave a comment