
Issue #20792 has been updated by Eregon (Benoit Daloze).
I think the advantage right now is that it doesn't require a mutable string to check.
`with_encoding` would always be the same as `.dup.force_encoding` (except slightly more efficient). It doesn't mutate the receiver. For the description use case you could then use `valid_encoding?` like in https://bugs.ruby-lang.org/issues/20792#note-3 That might compute the code range (if not already computed), but that's needed to know if the encoding is valid anyway, and interestingly it will remember this coderange for further operations on that new String. Using `forcible_encoding?` it can't remember the code range and so it would have to be recomputed on `force_encoding` or the next operation needing it. ---------------------------------------- Feature #20792: String#forcible_encoding? https://bugs.ruby-lang.org/issues/20792#change-110141 * Author: kddnewton (Kevin Newton) * Status: Open ---------------------------------------- I would like to add a method to String called `forcible_encoding?(encoding)`. This would return true or false depending on whether the receiver can be forced into the given encoding without breaking the string. It would effectively be an alias for: ```ruby def forcible_encoding?(enc) original = encoding result = force_encoding(enc).valid_encoding? force_encoding(original) result end ``` I would like this method because there are extremely rare but possible circumstances where source files are marked as binary but contain UTF-8-encoded characters. In that case I would like to check if it's possible to cleanly force UTF-8 before actually doing it. The code I'm trying to replace is here: https://github.com/ruby/prism/blob/d6e9b8de36b4d18debfe36e4545116539964ceeb/.... The pull request for the code is here: https://github.com/ruby/ruby/pull/11851. -- https://bugs.ruby-lang.org/