How to use the encoding class in Ruby

Overview

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.

Syntax

Encoding.name_list

Return value

The name_list property of the Encoding class returns a list of available encoding names.

Example

An example of using the name_list property of the Encoding class is as follows:

# Print the available encodings
puts "#{Encoding.name_list}"
# Create a string
str1 = "Welcome to Edpresso!"
# Get its encoding
puts "#{str1} encoding is : #{str1.encoding.name}"

Explanation

  • Line 2: We print all available encodings.
  • Wine 5: We create a string.
  • Line 8: We get the encoding of the string we created.
# Create a string
str2 = "Welcome to Edpresso"
# Print the default encoding
puts str2.encoding.name # UTF-8
# Change the encoding
str2.force_encoding("US-ASCII")
# Reprint the encoding
puts str2.encoding.name # US-ASCII

Explanation

  • Line 2: We create a string.
  • Line 5: We printed the default encoding name of the string, UFT-8.
  • Line 8: We using force_encoding to change the encoding of the string to another one.
  • Line 11: We print the new encoding to the console screen.