Method: String#to_utf8!

Defined in:
lib/openc3/core_ext/string.rb

#to_utf8!String

Converts a string to UTF-8 in place Assumes the string is Windows-1252 encoded if marked ASCII-8BIT and not UTF-8 compatible

Returns:

  • (String)

    UTF-8 encoded string



378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/openc3/core_ext/string.rb', line 378

def to_utf8!
  if self.encoding == Encoding::ASCII_8BIT
    if self.force_encoding('UTF-8').valid_encoding?
      return self
    else
      # Note: this will replace any characters without a valid conversion with space (shouldn't be possible from Windows-1252)
      return self.force_encoding('Windows-1252').encode!('UTF-8', invalid: :replace, undef: :replace, replace: ' ')
    end
  else
    # Note: this will replace any characters without a valid conversion with space
    self.encode!('UTF-8', invalid: :replace, undef: :replace, replace: ' ')
  end
end