The Encoding instance represents any character encoding in Ruby.
In Ruby, texts are encoded in UTF-8 by default. This is because UTF-8 is a multi-byte character encoding that allows a single character to take up between 1 and 4 bytes. Other encodings, such as UTF-7, UCS-2, UTF-16, etc., are also present. Even if the default encoding of all strings or texts in Ruby is UFT-8, we can convert it from one encoding to another.
The name_list
property of the Encoding class retrieves the list of all available encoding names.
Encoding.name_list
The name_list
property of the Encoding class returns a list of available encoding names.
An example of using the name_list
property of the Encoding class is as follows:
# Print the available encodingsputs "#{Encoding.name_list}"# Create a stringstr1 = "Welcome to Edpresso!"# Get its encodingputs "#{str1} encoding is : #{str1.encoding.name}"
# Create a stringstr2 = "Welcome to Edpresso"# Print the default encodingputs str2.encoding.name # UTF-8# Change the encodingstr2.force_encoding("US-ASCII")# Reprint the encodingputs str2.encoding.name # US-ASCII
UFT-8
.force_encoding
to change the encoding of the string to another one.