Mohamed El Mahallawy Mohamed El Mahallawy - 4 months ago 22
Ruby Question

Parsing string to add to URL-encoded URL

Given the string:

"Hello there world"


how can I create a URL-encoded string like this:

"Hello%20there%20world"


I would also like to know what to do if the string has other symbols too, like:

"hello there: world, how are you"


What would is the easiest way to do so? I was going to parse and then build some code for that.

Answer
require 'uri'

URI.encode("Hello there world")
#=> "Hello%20there%20world"
URI.encode("hello there: world, how are you")
#=> "hello%20there:%20world,%20how%20are%20you"

URI.decode("Hello%20there%20world")
#=> "Hello there world"