From: "Eregon (Benoit Daloze) via ruby-core" <ruby-core@...>
Date: 2024-10-09T22:34:34+00:00
Subject: [ruby-core:119500] [Ruby master Feature#20792] String#forcible_encoding?

Issue #20792 has been updated by Eregon (Benoit Daloze).


Right, that would also solve this specific usage.
However I think `String#with_encoding` is a good general method to have, as for instance there are [lots of `.dup.force_encoding`](https://github.com/search?q=.dup.force_encoding+language%3ARuby&type=code&l=Ruby).
It's one of the rare cases where Ruby core API don't have a nice way to do something in a non-mutating manner so that would fix it.
It's especially striking for frozen literal strings where one just wants it in some specific encoding, but currently one has to `"foo".dup.force_encoding(SOME_ENCODING)`.
There is `String#b` but that's only for the BINARY encoding (and the name is not really clear).

----------------------------------------
Feature #20792: String#forcible_encoding?
https://bugs.ruby-lang.org/issues/20792#change-110114

* 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/lib/prism/parse_result.rb#L15-L30.

The pull request for the code is here: https://github.com/ruby/ruby/pull/11851.



-- 
https://bugs.ruby-lang.org/
 ______________________________________________
 ruby-core mailing list -- ruby-core@ml.ruby-lang.org
 To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
 ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/