Using html entities in Ruby

HTML character entities are used to display reserved characters in a web page. The entire list of character entity references can be found here. Sometimes you may want to use HTML entities inside your ruby code. This is where gem htmlentities comes into picture. This is a simple library to facilitate encoding and decoding of character and numerical html entities in ruby. It works with only UTF-8 (or ASCII) strings only. make sure your system is set to display UTF-8 before using it.

You can install the gem by typing

gem install htmlentities

Encoding

You can encode HTML entities by calling encode method on HTMLEntities class. This method takes variable number of options as parameters

require 'htmlentities'
coder = HTMLEntities.new
string = "<élan>"
coder.encode(string, &options)

Decoding

You can decode HTML entities by calling decode method on HTMLEntities class.

require 'htmlentities'
coder = HTMLEntities.new
string = "&copy;"
coder.decode(string)

The various options and flavours in using the library can be found here.

Happy coding 🙂

Leave a comment