Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#scrub

str.scrub → new_str
str.scrub(repl) → new_str
str.scrub{|bytes|} → new_str

If the string is invalid byte sequence then replace invalid bytes with given replacement character, else returns self. If block is given, replace invalid bytes with returned value of the block.

Example
"abc\u3042\x81".scrub #=> "abc\u3042\uFFFD"
"abc\u3042\x81".scrub("*") #=> "abc\u3042*"
"abc\u3042\xE3\x80".scrub{|bytes| '<'+bytes.unpack('H*')[0]+'>' } #=> "abc\u3042<e380>"

Ruby version changes

  1. 3.0
See also #scrub! #scan #rstrip! #setbyte also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1