Skip to content

Instantly share code, notes, and snippets.

@hyuki
Last active March 5, 2019 12:39
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 hyuki/bbb72982e4257f86c48b85d7278f342c to your computer and use it in GitHub Desktop.
Save hyuki/bbb72982e4257f86c48b85d7278f342c to your computer and use it in GitHub Desktop.
compare_escape.rb - Compare CGI.escapeHTML, CGI.escape, and URI.encode.
CGI.escapeHTML('< > &') #=> &lt; &gt; &amp;
CGI.escape('< > &')     #=> %3C+%3E+%26
URI.encode('< > &')     #=> %3C%20%3E%20&

CGI.escapeHTML('https://example.com/')  #=> https://example.com/
CGI.escape('https://example.com/')      #=> https%3A%2F%2Fexample.com%2F
URI.encode('https://example.com/')      #=> https://example.com/

CGI.escapeHTML('結')   #=> 結
CGI.escape('結')       #=> %E7%B5%90
URI.encode('結')       #=> %E7%B5%90
#! /usr/bin/env ruby
require "cgi"
require "uri"
def doit(f, s)
print "#{f}('#{s}')\t#=> "
puts eval "#{f}('#{s}')"
end
[ "< > &", "https://example.com/", "結"].each do |s|
[ 'CGI.escapeHTML', 'CGI.escape', 'URI.encode' ].each do |f|
doit(f, s)
end
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment