Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
CGI::Util#escapeURIComponent
escapeURIComponent(string)
lib/cgi/util.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.4.1/lib/cgi/util.rb, line 41
def escapeURIComponent(string)
encoding = string.encoding
buffer = string.b
buffer.gsub!(/([^a-zA-Z0-9_.\-~]+)/) do |m|
'%' + m.unpack('H2' * m.bytesize).join('%').upcase
end
buffer.force_encoding(encoding)
end
URL-encode a string following RFC 3986 Space characters (+“ ”+) are encoded with (+“%20”+)
Example
url_encoded_string = CGI.escapeURIComponent("'Stop!' said Fred") # => "%27Stop%21%27%20said%20Fred"