os97673/regexp_m17n — pull request #112 by dawsonc (2014-08-10 04:56:55+00:00)
Title: Solved (for ALL encodings, including dummies)

My solution centers around an `if` that checks if the string argument's encoding is a dummy encoding. If it is, it uses `force_encoding` to change the string to UTF-8 encoding. If it isn't, it simply encodes the Regular Expression to match the string argument's encoding.

This works because when the string is encoded in a dummy encoding, you can't really transcode in or out of the format, but you can force the string to encode using a different encoding. This corrupts the data (because a character code in one encoding probably doesn't mean the same thing in another), but, critically, *will never change a non-empty string to an empty string*. Most of the time the conversion is 1 to 1, but for 4 encodings (specifically the 16- or 32-bit UTF encodings) the conversion results in some lost characters, but (and I have tested this) a 1-character string will never become a 0-character string, so the test for non-emptiness would never be impacted.

When the string is encoded in a non-dummy format, it is trivial to encode either the regex or the string itself into a common encoding. I've chosen to encode the regex, since that's the more efficient solution for large string arguments.

I had to make one modification to the tests. The very reason dummy encodings are marked as such is because Ruby does not know how to deal with them. Understandably, the runtime does not react very well to being told to translate something into one of these encodings, and calls an error when you call `encode(some_dummy_encoding)` on a string. To get around this, I changed the test to use `'.'.force_encoding` with dummy encodings (change the string's encoding without actually transcoding it).

I hope I've explained this well enough. Thanks for hosting this competition, by the way. This has been a fun problem to wrap my head.

Best,
Charles