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
string.c
View on GitHub ↗
static VALUE
str_scrub(int argc, VALUE *argv, VALUE str)
{
VALUE repl = argc ? (rb_check_arity(argc, 0, 1), argv[0]) : Qnil;
VALUE new = rb_str_scrub(str, repl);
return NIL_P(new) ? str_duplicate(rb_cString, str): new;
}
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
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-