File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -40,6 +40,33 @@ str << "123"
4040str.to_s
4141```
4242
43+ ## TL;DR
44+
45+ For a most cases, you can just use a function like:
46+
47+ ``` ruby
48+ def scrub_invalid_bytes (string , encoding: Encoding ::UTF_8 )
49+ return nil if string.nil?
50+ replace = " ?"
51+ string = string.scrub(replace)
52+ string.encode(encoding)
53+ rescue Encoding ::UndefinedConversionError , Encoding ::InvalidByteSequenceError
54+ encode_unconvertable_bytes = {
55+ :invalid => :replace ,
56+ :undef => :replace ,
57+ :replace => replace
58+ }
59+ string.encode(encoding, encode_unconvertable_bytes)
60+ rescue Encoding ::ConverterNotFoundError
61+ encode_no_converter = {
62+ :invalid => :replace ,
63+ :replace => replace
64+ }
65+
66+ string.dup.force_encoding(encoding).encode(encode_no_converter)
67+ end
68+ ```
69+
4370## About
4471
4572Encoding Exceptions:
You can’t perform that action at this time.
0 commit comments