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:
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:
'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.
The supported Unicode version.
The name of the encoding.
Encoding::UTF_8.name #=> "UTF-8"
The name of the encoding.
Encoding::UTF_8.name #=> "UTF-8"
static VALUE
rb_enc_aliases(VALUE klass)
{
VALUE aliases[2];
aliases[0] = rb_hash_new();
aliases[1] = rb_ary_new();
GLOBAL_ENC_TABLE_LOCKING(enc_table) {
st_foreach(enc_table->names, rb_enc_aliases_enc_i, (st_data_t)aliases);
}
return aliases[0];
}
Returns the hash of available encoding alias and original encoding name.
Encoding.aliases
#=> {"BINARY"=>"ASCII-8BIT", "ASCII"=>"US-ASCII", "ANSI_X3.4-1968"=>"US-ASCII",
"SJIS"=>"Windows-31J", "eucJP"=>"EUC-JP", "CP932"=>"Windows-31J"}
static VALUE
enc_compatible_p(VALUE klass, VALUE str1, VALUE str2)
{
rb_encoding *enc;
if (!enc_capable(str1)) return Qnil;
if (!enc_capable(str2)) return Qnil;
enc = rb_enc_compatible(str1, str2);
if (!enc) return Qnil;
return rb_enc_from_encoding(enc);
}
Checks the compatibility of two objects.
If the objects are both strings they are compatible when they are concatenatable. The encoding of the concatenated string will be returned if they are compatible, nil if they are not.
Encoding.compatible?("\xa1".force_encoding("iso-8859-1"), "b") #=> #<Encoding:ISO-8859-1> Encoding.compatible?( "\xa1".force_encoding("iso-8859-1"), "\xa1\xa1".force_encoding("euc-jp")) #=> nil
If the objects are non-strings their encodings are compatible when they have an encoding and:
-
Either encoding is US-ASCII compatible
-
One of the encodings is a 7-bit encoding