End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
String#partition
partition(string_or_regexp) → [head, match, tail]
string.c
View on GitHub ↗
static VALUE
rb_str_partition(VALUE str, VALUE sep)
{
long pos;
sep = get_pat_quoted(sep, 0);
if (RB_TYPE_P(sep, T_REGEXP)) {
if (rb_reg_search(sep, str, 0, 0) < 0) {
goto failed;
}
VALUE match = rb_backref_get();
struct re_registers *regs = RMATCH_REGS(match);
pos = BEG(0);
sep = rb_str_subseq(str, pos, END(0) - pos);
}
else {
pos = rb_str_index(str, sep, 0);
if (pos < 0) goto failed;
}
return rb_ary_new3(3, rb_str_subseq(str, 0, pos),
sep,
rb_str_subseq(str, pos+RSTRING_LEN(sep),
RSTRING_LEN(str)-pos-RSTRING_LEN(sep)));
failed:
return rb_ary_new3(3, str_duplicate(rb_cString, str), str_new_empty_String(str), str_new_empty_String(str));
}
Returns a 3-element array of substrings of self.
Matches a pattern against self, scanning from the beginning. The pattern is:
-
string_or_regexpitself, if it is aRegexp. -
Regexp.quote(string_or_regexp), ifstring_or_regexpis a string.
If the pattern is matched, returns pre-match, first-match, post-match:
Example
'hello'.partition('l') # => ["he", "l", "lo"] 'hello'.partition('ll') # => ["he", "ll", "o"] 'hello'.partition('h') # => ["", "h", "ello"] 'hello'.partition('o') # => ["hell", "o", ""] 'hello'.partition(/l+/) #=> ["he", "ll", "o"] 'hello'.partition('') # => ["", "", "hello"] 'тест'.partition('т') # => ["", "т", "ест"] 'こんにちは'.partition('に') # => ["こん", "に", "ちは"]
If the pattern is not matched, returns a copy of self and two empty strings:
Example
'hello'.partition('x') # => ["hello", "", ""]
Related: String#rpartition, String#split.
Ruby version changes
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-