Skip to content

Instantly share code, notes, and snippets.

@emmahsax
Created December 3, 2020 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emmahsax/f0f320597d82ce2578eb0f7595f08909 to your computer and use it in GitHub Desktop.
Save emmahsax/f0f320597d82ce2578eb0f7595f08909 to your computer and use it in GitHub Desktop.
Turn any string into a string fit for URLs

URL Encode a string

If you ever have a string that doesn't play nice with URLs, that's probably because it has spaces, or slashes, or anything like that. So, with this easy method, we can turn that string into a URL-friendly string!

def url_encode(str)
  str.b.gsub(/[^a-zA-Z0-9_\-.~]/n) { |m| format('%%%<val>02X', val: m.unpack1('C')) }
end

> url_encode('foo/bar')
=> "foo%2Fbar"
> url_encode('hello world')
=> "hello%20world"
> url_encode('foo-bar/hello world')
=> "foo-bar%2Fhello%20world"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment