Skip to content

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

instance method

String#scrub

scrub(replacement_string = default_replacement) → new_string
scrub{|bytes| ... } → new_string

Returns a copy of self with each invalid byte sequence replaced by the given replacement_string.

With no block given and no argument, replaces each invalid sequence with the default replacement string ("�" for a Unicode encoding, '?' otherwise):

Example
s = "foo\x81\x81bar"
s.scrub # => "foo��bar"

With no block given and argument replacement_string given, replaces each invalid sequence with that string:

Example
"foo\x81\x81bar".scrub('xyzzy') # => "fooxyzzyxyzzybar"

With a block given, replaces each invalid sequence with the value of the block:

Example
"foo\x81\x81bar".scrub {|bytes| p bytes; 'XYZZY' }
# => "fooXYZZYXYZZYbar"

Output:

Example
"\x81"
"\x81"

Ruby version changes

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