How do I encode/decode HTML entities in Ruby?

To encode the characters, you can use CGI.escapeHTML:

string = CGI.escapeHTML('test "escaping" <characters>')

To decode them, there is CGI.unescapeHTML:

CGI.unescapeHTML("test &quot;unescaping&quot; &lt;characters&gt;")

Of course, before that you need to include the CGI library:

require 'cgi'

And if you’re in Rails, you don’t need to use CGI to encode the string. There’s the h method.

<%= h 'escaping <html>' %>

Leave a Comment