class String def sjisable str = self #変換テーブル上の文字を下の文字に置換する from_chr = "\u{301C 2212 00A2 00A3 00AC 2013 2014 2016 203E 00A0 00F8 203A}" to_chr = "\u{FF5E FF0D FFE0 FFE1 FFE2 FF0D 2015 2225 FFE3 0020 03A6 3009}" str.tr!(from_chr, to_chr) #変換テーブルから漏れた不正文字は?に変換し、さらにUTF8に戻すことで今後例外を出さないようにする str = str.encode("Windows-31J","UTF-8",:invalid => :replace,:undef=>:replace).encode("UTF-8","Windows-31J") end
![Windows-31Jに変換する時の例外を防止するためのString拡張 - Qiita](https://cdn-ak-scissors.b.st-hatena.com/image/square/ef44dbd572c629820a0080952869035b834f6083/height=288;version=1;width=512/https%3A%2F%2Fqiita-user-contents.imgix.net%2Fhttps%253A%252F%252Fcdn.qiita.com%252Fassets%252Fpublic%252Farticle-ogp-background-412672c5f0600ab9a64263b751f1bc81.png%3Fixlib%3Drb-4.0.0%26w%3D1200%26mark64%3DaHR0cHM6Ly9xaWl0YS11c2VyLWNvbnRlbnRzLmltZ2l4Lm5ldC9-dGV4dD9peGxpYj1yYi00LjAuMCZ3PTk3MiZoPTM3OCZ0eHQ9V2luZG93cy0zMUolRTMlODElQUIlRTUlQTQlODklRTYlOEYlOUIlRTMlODElOTklRTMlODIlOEIlRTYlOTklODIlRTMlODElQUUlRTQlQkUlOEIlRTUlQTQlOTYlRTMlODIlOTIlRTklOTglQjIlRTYlQUQlQTIlRTMlODElOTklRTMlODIlOEIlRTMlODElOUYlRTMlODIlODElRTMlODElQUVTdHJpbmclRTYlOEIlQTElRTUlQkMlQjUmdHh0LWFsaWduPWxlZnQlMkN0b3AmdHh0LWNvbG9yPSUyMzIxMjEyMSZ0eHQtZm9udD1IaXJhZ2lubyUyMFNhbnMlMjBXNiZ0eHQtc2l6ZT01NiZzPTNhNmY4YjEwMmRkZjdmZjA3ZjIyYWM2MjIxNTYxYmUw%26mark-x%3D142%26mark-y%3D57%26blend64%3DaHR0cHM6Ly9xaWl0YS11c2VyLWNvbnRlbnRzLmltZ2l4Lm5ldC9-dGV4dD9peGxpYj1yYi00LjAuMCZoPTc2Jnc9NzcwJnR4dD0lNDB5dWdvLXlhbWFtb3RvJnR4dC1jb2xvcj0lMjMyMTIxMjEmdHh0LWZvbnQ9SGlyYWdpbm8lMjBTYW5zJTIwVzYmdHh0LXNpemU9MzYmdHh0LWFsaWduPWxlZnQlMkN0b3Amcz1hMTNlYTlkZGMxZWRjYjAyYTY0ODdlMjY0YmQ0MDI0Ng%26blend-x%3D142%26blend-y%3D486%26blend-mode%3Dnormal%26s%3D29721fcdf05dc26d2fdc61f7b2fbb87f)