Parsing string to add to URL-encoded URL

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

In 2019, URI.encode is obsolete and should not be used.


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"

Solution 2 - Ruby on-Rails

While the current answer says to utilize URI.encode that has been deprecated and obsolete since Ruby 1.9.2. It is better to utilize CGI.escape or ERB::Util.url_encode.

Solution 3 - Ruby on-Rails

Ruby's URI is useful for this. You can build the entire URL programmatically and add the query parameters using that class, and it'll handle the encoding for you:

require 'uri'

uri = URI.parse('http://foo.com')
uri.query = URI.encode_www_form(
  's' => "Hello there world"
)
uri.to_s # => "http://foo.com?s=Hello+there+world"

The examples are useful:

URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
#=> "q=ruby&lang=en"
URI.encode_www_form("q" => "ruby", "lang" => "en")
#=> "q=ruby&lang=en"
URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
#=> "q=ruby&q=perl&lang=en"
URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
#=> "q=ruby&q=perl&lang=en"

These links might also be useful:

Solution 4 - Ruby on-Rails

If anyone is interested, the newest way to do this is doing in ERB:

    <%= u "Hello World !" %>

This will render:

> Hello%20World%20%21

u is short for url_encode

You can find the docs here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMohamed El MahallawyView Question on Stackoverflow
Solution 1 - Ruby on-RailsArie XiaoView Answer on Stackoverflow
Solution 2 - Ruby on-RailsBenjaminView Answer on Stackoverflow
Solution 3 - Ruby on-Railsthe Tin ManView Answer on Stackoverflow
Solution 4 - Ruby on-RailsoschvrView Answer on Stackoverflow