dionin
dionin

Reputation: 19

Ruby comparing strings

I'm trying to compare message[0] with "CONNECT" but it just fails:

puts message[0].dump 
->"\x00C\x00O\x00N\x00N\x00E\x00C\x00T\x00"
puts "CONNECT".dump
->"CONNECT"

Can somebody explain me why?

Upvotes: 1

Views: 284

Answers (2)

Arne Brasseur
Arne Brasseur

Reputation: 1518

It seems you have a lot of NULL characters in your string. It would be best to figure out where they are coming from, but to just remove them you can use this.

 def remove_null_chrs(str) 
     str.unpack('C*').select{|x|x != 0}.pack('C*')
 end

For instance

remove_null_chrs("\x00C\x00O\x00N\x00N\x00E\x00C\x00T\x00")
=> "CONNECT"

Upvotes: 2

Ismael
Ismael

Reputation: 16710

message[0] is in different encoding

Try this message[0].encode("UTF-8", :invalid=>:replace, :replace=>"?")

If it does not work you have to try different encodings. I think this answer is valid only for 1.9.* version. For older versions I think you have to require iconv

Upvotes: 0

Related Questions