Skip to content

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

instance method

Encoding::InvalidByteSequenceError#source_encoding

() -> ::Encoding
ecerr.source_encoding → encoding

Returns the source encoding as an encoding object.

Note that the result may not be equal to the source encoding of the encoding converter if the conversion has multiple steps.

Example
ec = Encoding::Converter.new("ISO-8859-1", "EUC-JP") # ISO-8859-1 -> UTF-8 -> EUC-JP
begin
  ec.convert("\xa0") # NO-BREAK SPACE, which is available in UTF-8 but not in EUC-JP.
rescue Encoding::UndefinedConversionError
  p $!.source_encoding              #=> #<Encoding:UTF-8>
  p $!.destination_encoding         #=> #<Encoding:EUC-JP>
  p $!.source_encoding_name         #=> "UTF-8"
  p $!.destination_encoding_name    #=> "EUC-JP"
end