Take the 2-minute tour ×


String test="hi\000\000\000"

Problem: Some methods require a string to be without nulls, how can I delete all null values of a string?

.split("\000",1) gives me an error: 'force_encoding' method doesn't exist
.gsub('\000','') does nothing
share|improve this question
'\000' in Ruby evaluates to "\\000" –  Bob Aman Sep 23 '11 at 7:40

3 Answers 3

up vote 6 down vote accepted

Even more simple:

share|improve this answer
Easiest solution, thank you –  Onetimeposter123 Sep 23 '11 at 9:45

Try using double quotes, so test.gsub("\000", '').

share|improve this answer
Forgot that ' ' doesn't parse escape characters, thanks. (5 minutes till I can accept the answer. –  Onetimeposter123 Sep 23 '11 at 7:37

Right now I tried this in JRuby and it worked:

test.gsub(/\000/, '')

Note that I am using a regex in the gsub and not a string.

share|improve this answer
Works as well (though my natural enemy is Regex) –  Onetimeposter123 Sep 23 '11 at 7:38
Regexp literal replacements are ever-so-slightly faster than single-character-string replacements in MRI. Not sure about JRuby. –  Bob Aman Sep 23 '11 at 7:44
@Bob Aman: Indeed. Do you know why? Anyway, I think a regexp is overkill for this case. –  undur_gongor Sep 23 '11 at 7:50
Not really. My guess would be that the Regexp code goes through a better optimized code-path. –  Bob Aman Sep 26 '11 at 8:03

Your Answer


