DevToolsForYou

URL Encoder and Decoder in Ruby — Code Examples

URL Encoder and Decoder in RubyUse the online tool →

URL encoding (percent-encoding) replaces characters that are not allowed in URLs with a percent sign followed by their hexadecimal value. Here is how to encode and decode URL components in each language.

Ruby provides CGI.escape for form-style encoding and URI.encode_www_form_component for query strings. Both are in the standard library.

Ruby
require 'cgi'
require 'uri'

input = "hello world & foo=bar"

# Encode a query parameter value (spaces as +)
encoded = CGI.escape(input)
puts encoded # hello+world+%26+foo%3Dbar

# Decode
decoded = CGI.unescape("hello+world+%26+foo%3Dbar")
puts decoded # hello world & foo=bar

# RFC 3986 percent-encoding (spaces as %20, for path segments)
rfc_encoded = URI.encode_www_form_component(input)
puts rfc_encoded # hello+world+%26+foo%3Dbar

# Build a query string from a hash
qs = URI.encode_www_form(q: "hello world", page: 1)
puts qs # q=hello+world&page=1

# Parse query string
params = URI.decode_www_form("q=hello+world&page=1").to_h
puts params["q"] # hello world
Notes & gotchas
  • CGI.escape encodes spaces as + (form encoding); URI.encode_www_form_component also encodes as + for query strings.
  • For strict RFC 3986 path-segment encoding (spaces as %20), use ERB::Util.url_encode or CGI.escape + replace.
  • URI.encode_www_form is the cleanest way to build a query string from a hash.
Try it in your browser

Need to url encode/decode without writing code? The URL Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open URL Encode/Decode
URL Encoder and Decoder in other languages