Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

String#encode

encode(dst_encoding = Encoding.default_internal, **enc_opts) → string
encode(dst_encoding, src_encoding, **enc_opts) → string

Returns a copy of self transcoded as determined by dst_encoding. By default, raises an exception if self contains an invalid byte or a character not defined in dst_encoding; that behavior may be modified by encoding options; see below.

With no arguments:

  • Uses the same encoding if Encoding.default_internal is nil (the default):

    Example
    Encoding.default_internal # => nil
    s = "Ruby\x99".force_encoding('Windows-1252')
    s.encoding                # => #<Encoding:Windows-1252>
    s.bytes                   # => [82, 117, 98, 121, 153]
    t = s.encode              # => "Ruby\x99"
    t.encoding                # => #<Encoding:Windows-1252>
    t.bytes                   # => [82, 117, 98, 121, 226, 132, 162]
    
  • Otherwise, uses the encoding Encoding.default_internal:

    Example
    Encoding.default_internal = 'UTF-8'
    t = s.encode              # => "Ruby™"
    t.encoding                # => #<Encoding:UTF-8>
    

With only argument dst_encoding given, uses that encoding:

Example
s = "Ruby\x99".force_encoding('Windows-1252')
s.encoding            # => #<Encoding:Windows-1252>
t = s.encode('UTF-8') # => "Ruby™"
t.encoding            # => #<Encoding:UTF-8>

With arguments dst_encoding and src_encoding given, interprets self using src_encoding, encodes the new string using dst_encoding:

Example
s = "Ruby\x99"
t = s.encode('UTF-8', 'Windows-1252') # => "Ruby™"
t.encoding                            # => #<Encoding:UTF-8>

Optional keyword arguments enc_opts specify encoding options; see Encoding Options.

Please note that, unless invalid: :replace option is given, conversion from an encoding enc to the same encoding enc (independent of whether enc is given explicitly or implicitly) is a no-op, i.e. the string is simply copied without any changes, and no exceptions are raised, even if there are invalid bytes.

See also #encode! #empty? #each_line #encoding also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0