WedTM
WedTM

Reputation: 2647

Can't Parse String in Ruby

I have the following string that I would like to split on the \xA7 character.

\xFF$New Server\xA77\xA750

The problem being is that I can't figure out how to tell Ruby to split it correctly on the \xA7 marker.

This is the error I get:

>> "\xFF$New Server\xA77\xA750".split("\xA7")
ArgumentError: invalid byte sequence in UTF-8
from (irb):26:in `split'
from (irb):26
from /Users/wedtm/.rbenv/versions/1.9.2-p290/bin/irb:12:in `<main>'

Upvotes: 1

Views: 252

Answers (2)

lwe
lwe

Reputation: 2625

When forcing the encoding to BINARY you can work around that issue, though not sure if it's the correct solution or breaks other things...

input = "\xFF$New Server\xA77\xA750".force_encoding('BINARY')
split = "\xA7".force_encoding('BINARY')
input.split(split) # => ["\xFF$New Server", "7", "50"]

Upvotes: 2

pguardiario
pguardiario

Reputation: 55012

The problem is that the string has an invalid utf-8 byte sequence. If you don't care about that try putting this at the top of your document:

# coding: ascii

Upvotes: 0

Related Questions