Ruby test for "\ 0" null?

I have some odd characters appearing in lines that break the script. From what I can say put badstring for the console, they are "\0\0\0\0" .

I would like to test this so that I can ignore them ... but how?

thought for <? 22> and empty? for?!?

 > badstring = "\0" => "\u0000" > badstring.blank? NoMethodError: undefined method `blank?' for "\u0000":String from (irb):97 from /Users/meltemi/.rvm/rubies/ruby-2.0.0-p195/bin/irb:16:in `<main>' > badstring.empty? => false > badstring.nil? => false 

Edit: trying to recreate this in irb, but with problems:

 > test1 = "\0\0\0\0" => "\u0000\u0000\u0000\u0000" > test2 = '\0\0\0\0' => "\\0\\0\\0\\0" 

what I want is the string "\0\0\0\0" , so I can find a way to test if mystring == "\0\0\0\0" or something like that.

+4
source share
3 answers

You can simply remove the characters "\0" with

 badstring.delete!("\0") 

Full example

 badstring = "\0" badstring.delete!("\0") badstring.empty? #=> true 

Use delete instead of delete! if you want to keep the original string.

+3
source

First of all, blank? is an assistant to Rails. Try instead:

 badstring =~ /\x00/ 

if it returns an integer, then this string includes "\0" , if it returns nil , then this string does not include "\0" .

+3
source

It looks like we need to check the encoding and characters here. You can check the type of string encoding for "string".encoding . You can then see which character codes are actually used here with badstring.chars.map(&:ord) . Then you can replace / remove characters with character_code.chr(encoding) .

+3
source

Source: https://habr.com/ru/post/1481790/


All Articles