Skip to content

Instantly share code, notes, and snippets.

Last active December 10, 2015 20:58
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
String#replace_invalid_bytes that replaces invalid bytes in a string
# -*- coding: utf-8 -*-
class String
def replace_invalid_bytes(replace = nil)
if block_given?
if replace
warn 'block not used' if $VERBOSE
elsif replace.nil?
raise ArgumentError, 'an argument or a block must be given'
return self if valid_encoding?
if replace
r = String.try_convert(replace) or
raise TypeError, "can't convert #{replace.class} into String"
each_char.inject('') { |s, c|
s << (c.valid_encoding? ? c : r)
each_char.inject('') { |s, c|
s << (c.valid_encoding? ? c : yield(*c.bytes))
puts "あい\x80\xffう".replace_invalid_bytes('[?]')
#=> あい[?][?]う
puts "あい\x80\xffう".replace_invalid_bytes { |b| "<%02X>" % b }
#=> あい<80><FF>う
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment