Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
String#strip
static VALUE
rb_str_strip(int argc, VALUE *argv, VALUE str)
{
const char *start;
rb_len_t olen, loffset, roffset;
rb_encoding *enc = STR_ENC_GET(str);
RSTRING_GETMEM(str, start, olen);
if (argc > 0) {
char table[TR_TABLE_SIZE];
VALUE del = 0, nodel = 0;
tr_setup_table_multi(table, &del, &nodel, str, argc, argv);
/* the selector conversion may have modified str */
enc = STR_ENC_GET(str);
RSTRING_GETMEM(str, start, olen);
loffset = lstrip_offset_table(str, start, start+olen, enc, table, del, nodel);
roffset = rstrip_offset_table(str, start+loffset, start+olen, enc, table, del, nodel);
}
else {
loffset = lstrip_offset(str, start, start+olen, enc);
roffset = rstrip_offset(str, start+loffset, start+olen, enc);
}
if (loffset <= 0 && roffset <= 0) return str_duplicate(rb_cString, str);
return rb_str_subseq(str, loffset, olen-loffset-roffset);
}
Returns a copy of self with leading and trailing whitespace removed; see Whitespace in Strings:
whitespace = "\x00\t\n\v\f\r " s = whitespace + 'abc' + whitespace # => "\u0000\t\n\v\f\r abc\u0000\t\n\v\f\r " s.strip # => "abc"
If selectors are given, removes characters of selectors from both ends of self:
s = "---abc+++" s.strip("-+") # => "abc" s.strip("+-") # => "abc"
selectors must be valid character selectors (see Character Selectors), and may use any of its valid forms, including negation, ranges, and escapes:
"01234abc56789".strip("0-9") # "abc" "01234abc56789".strip("0-9", "^4-6") # "4abc56"
Related: see Converting to New String.
Ruby version changes
-
4.0
-
String#strip,strip!,lstrip,lstrip!,rstrip, andrstrip!are extended to accept*selectorsarguments. [Feature #21552]
-
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-