Skip to content
On this page

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class · Ruby 4.1

Encoding

< Object 4 instance methods 10 class methods

An Encoding instance represents a character encoding usable in Ruby. It is defined as a constant under the Encoding namespace. It has a name and, optionally, aliases:

Example
Encoding::US_ASCII.name  # => "US-ASCII"
Encoding::US_ASCII.names # => ["US-ASCII", "ASCII", "ANSI_X3.4-1968", "646"]

A Ruby method that accepts an encoding as an argument will accept:

  • An Encoding object.

  • The name of an encoding.

  • An alias for an encoding name.

These are equivalent:

Example
'foo'.encode(Encoding::US_ASCII) # Encoding object.
'foo'.encode('US-ASCII')         # Encoding name.
'foo'.encode('ASCII')            # Encoding alias.

For a full discussion of encodings and their uses, see the Encodings document.

Encoding::ASCII_8BIT is a special-purpose encoding that is usually used for a string of bytes, not a string of characters. But as the name indicates, its characters in the ASCII range are considered as ASCII characters. This is useful when you use other ASCII-compatible encodings.

Class methods 10

Instance methods 4

Constants

The supported Unicode version.

Attributes
Read

The name of the encoding.

Example
Encoding::UTF_8.name      #=> "UTF-8"
Read

The name of the encoding.

Example
Encoding::UTF_8.name      #=> "UTF-8"

Ruby version changes 6

  1. 3.3
    • Encoding#replicate has been removed, it was already deprecated. [Feature #18949]

  2. 3.2
    • Encoding#replicate has been deprecated and will be removed in 3.3. [Feature #18949]

    • The dummy Encoding::UTF_16 and Encoding::UTF_32 encodings no longer try to dynamically guess the endian based on a byte order mark. Use Encoding::UTF_16BE/UTF_16LE and Encoding::UTF_32BE/UTF_32LE instead. This change speeds up getting the encoding of a String. [Feature #18949]

    • Limit maximum encoding set size by 256. If exceeding maximum size, EncodingError will be raised. [Feature #18949]

  3. 3.0