class IRB::Irb

def encode_with_invalid_byte_sequence(str, enc)

def encode_with_invalid_byte_sequence(str, enc)
  conv = Encoding::Converter.new(str.encoding, enc)
  dst = String.new
  begin
    ret = conv.primitive_convert(str, dst)
    case ret
    when :invalid_byte_sequence
      conv.insert_output(conv.primitive_errinfo[3].dump[1..-2])
      redo
    when :undefined_conversion
      c = conv.primitive_errinfo[3].dup.force_encoding(conv.primitive_errinfo[1])
      conv.insert_output(c.dump[1..-2])
      redo
    when :incomplete_input
      conv.insert_output(conv.primitive_errinfo[3].dump[1..-2])
    when :finished
    end
    break
  end while nil
  dst
end