Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby test for "\0" null?

Tags:

string

null

ruby

I have some odd characters showing up in strings that are breaking a script. From what I can tell by put badstring to console they are "\0\0\0\0".

I'd like to test for this so I can ignore them...but how?

thought that's what blank? and empty? were 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 having trouble:

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

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

like image 765
Meltemi Avatar asked May 20 '13 15:05

Meltemi


2 Answers

First of all blank? is a Rails helper. Try this instead:

badstring =~ /\x00/ 

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

like image 186
Sachin Singh Avatar answered Nov 15 '22 07:11

Sachin Singh


You could just remove "\0" chars 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 around.

like image 22
Patrick Oscity Avatar answered Nov 15 '22 09:11

Patrick Oscity