class String

include Comparable[String]

A sequence of characters, always valid UTF-8. Immutable: methods that change a string (#upcase, #sub, #insert) return a new one, and String::Builder is the mutable buffer to build one piece by piece.

Indices and lengths count characters (Unicode code points), not bytes: size is the number of characters and bytesize the number of bytes. Only #bytes, #getbyte, #each_byte and #bytesize work on bytes. A negative index counts from the end. Binary data is Bytes: convert with #to_bytes and Bytes#decode.

s = "héllo"
s.size                  # => 5
s.bytesize              # => 6
s[1]                    # => "é"
s.upcase                # => "HÉLLO"
s.sub(/l+/, "L")        # => "héLo"

<prelude>:1941

Classes and modules

Class methods

def self.build(&: (String::Builder) -> Void) -> String

The string the block builds: it receives an empty String::Builder and the result is the builder's contents.

String.build { |b| b << "a" << "b"; b.push("c") }   # => "abc"

<prelude>:1951

Methods

def +(other: String) -> String

The string followed by other.

<prelude>:1954

def *(count: Int) -> String

The string repeated count times; empty when count is 0 or negative.

"ab" * 3                # => "ababab"

<prelude>:1961

def %(args: Array[Object]) -> String

The string as a format, with args as the values of its conversions, as Kernel#format formats them: %d %i %s %f %e %g %x %X %o %b %c %%, with the flags -, 0, + and space, a width and a precision. A conversion without a value formats nil.

Raises

ArgumentError for a conversion it does not know (%p).

"%s-%05d" % ["a", 42]   # => "a-00042"
"%.2f" % 3.14159        # => "3.14"

<prelude>:1975

def <=>(other: String) -> Int

Compares by code points (the order of the UTF-8 bytes): -1, 0 or 1. Upper case comes before lower case; #casecmp ignores case.

<prelude>:1978

def ==(other: Object) -> Bool

Whether other is a string with the same characters (a Symbol is not equal to a string).

<prelude>:1981

def size -> Int

The number of characters (code points), not bytes.

<prelude>:1983

def length -> Int

The number of characters: the same as size.

<prelude>:1985

def bytesize -> Int

The number of bytes of the UTF-8 encoding.

<prelude>:1987

def empty? -> Bool

Whether the string has no character.

<prelude>:1989

def [](index: Int) -> String

The character at character index index, counting from the end when negative.

Raises

IndexError when index is out of range: #[]? returns nil instead.

"héllo"[1]              # => "é"
"héllo"[-1]             # => "o"
"héllo"[5]              # raises IndexError

<prelude>:2003

def [](range: Range[Int]) -> String

The characters in range (character indices, negative ones from the end). The end is cut to the string's; a start equal to the size gives an empty string.

Raises

IndexError when the start is beyond the size or before the beginning.

"hello"[1..2]           # => "el"
"hello"[1...-1]         # => "ell"
"hello"[3..10]          # => "lo"
"hello"[6..]            # raises IndexError

<prelude>:2019

def []?(index: Int) -> String?

The character at character index index, or nil when it is out of range.

<prelude>:2022

def chars -> Array[String]

The characters, each a string of one code point (#graphemes keeps a combining mark with its base).

<prelude>:2025

def bytes -> Array[Int]

The bytes of the UTF-8 encoding, each 0 to 255.

"hé".bytes              # => [104, 195, 169]

<prelude>:2031

def lines -> Array[String]

The lines, each with its "\n" (or "\r\n"); the last has none when the string does not end with one. Only "\n" ends a line. Empty for an empty string.

<prelude>:2035

def split -> Array[String]

The fields separated by runs of whitespace (Unicode whitespace), without empty fields at either end.

" a  b\tc\n".split      # => ["a", "b", "c"]

<prelude>:2042

def split(separator: String) -> Array[String]

The fields separated by separator. Empty fields at the end are dropped; those between separators are kept. A separator of one space splits on whitespace as split without one does, and an empty one gives the characters.

"a,b,,c,,".split(",")   # => ["a", "b", "", "c"]
"abc".split("")         # => ["a", "b", "c"]

<prelude>:2052

def split(separator: Regexp) -> Array[String]

The fields separated by matches of separator, as Ruby splits: the groups of the separator, if it has any, follow the field before it, an empty match where a field starts separates nothing, and empty fields at the end are dropped.

"a1b22c".split(/\d+/)   # => ["a", "b", "c"]
"a1b2c".split(/(\d)/)   # => ["a", "1", "b", "2", "c"]

<prelude>:2062

def scan(pattern: Regexp) -> Array[String]

The text of every match of pattern, in order. Unlike Ruby's, the result is the whole matches even when pattern has groups: use #matches for the groups.

"a1b22".scan(/\d+/)       # => ["1", "22"]
"a1b22".scan(/(\w)(\d)/)  # => ["a1", "b2"]

<prelude>:2071

def match(pattern: Regexp) -> MatchData?

The first match of pattern, or nil when there is none.

m = "on 2024-10".match(/(\d+)-(\d+)/)
m.nil?                  # => false
"abc".match(/\d/)       # => nil

<prelude>:2079

def matches(pattern: Regexp) -> Array[MatchData]

Every match, with its groups (scan gives the matched text only).

"a1b2".matches(/(\w)(\d)/).map { |m| m[2] }   # => ["1", "2"]

<prelude>:2085

def match?(pattern: Regexp) -> Bool

Whether pattern matches somewhere in the string.

<prelude>:2087

def =~(pattern: Regexp) -> Int?

The character index of the first match of pattern, or nil when there is none.

"héllo" =~ /l/          # => 2
"héllo" =~ /z/          # => nil

<prelude>:2095

def sub(pattern: String, replacement: String) -> String

The string with the first occurrence of pattern replaced by replacement; the string itself when there is none. The replacement is read as with a Regexp: \0 and \& are the match, \` and \' the text before and after it, \\ a backslash.

<prelude>:2100

def sub(pattern: Regexp, replacement: String) -> String

The string with the first match of pattern replaced by replacement; the string itself when there is none. In replacement, \1 to \9 and \k<name> are the groups (empty when a group took no part), \0 and \& the match, \` and \' the text before and after it, and \\ a backslash.

"a1b2".sub(/\d/, "<\\0>")                  # => "a<1>b2"
"a=1".sub(/(\w)=(\w)/, "\\2=\\1")          # => "1=a"
"a=1".sub(/(?<k>\w)=(?<v>\w)/, "\\k<v>")  # => "1"

<prelude>:2112

def gsub(pattern: String, replacement: String) -> String

The string with every occurrence of pattern replaced by replacement, read as #sub reads it. An empty pattern matches before each character and at the end.

"a.b.c".gsub(".", "-")  # => "a-b-c"
"abc".gsub("", "-")     # => "-a-b-c-"

<prelude>:2121

def gsub(pattern: Regexp, replacement: String) -> String

The string with every match of pattern replaced by replacement, read as #sub reads it.

"a1b2".gsub(/(\w)(\d)/, "\\2\\1")   # => "1a2b"

<prelude>:2128

def upcase -> String

The string in upper case, with Unicode's full mappings ("ß" becomes "SS").

"héllo ß".upcase        # => "HÉLLO SS"

<prelude>:2135

def downcase -> String

The string in lower case (Unicode).

<prelude>:2137

def capitalize -> String

The string with its first character in upper case and the rest in lower case (Unicode).

"hÉLLO wORLD".capitalize  # => "Héllo world"

<prelude>:2144

def swapcase -> String

The string with upper case changed to lower case and lower case to upper case (Unicode).

<prelude>:2147

def strip -> String

The string without leading and trailing whitespace. Whitespace is Unicode's (a no-break space is one); unlike Ruby's, a trailing NUL is kept.

"\t a b \n".strip       # => "a b"

<prelude>:2155

def lstrip -> String

The string without leading whitespace (Unicode's, as strip).

<prelude>:2157

def rstrip -> String

The string without trailing whitespace (Unicode's, as strip).

<prelude>:2159

def chomp -> String

The string without one trailing "\n", "\r\n" or "\r".

"a\r\n".chomp           # => "a"
"a\n\n".chomp           # => "a\n"

<prelude>:2166

def chop -> String

The string without its last character; empty for an empty string. Unlike Ruby's, a final "\r\n" loses only its "\n".

<prelude>:2169

def start_with?(prefix: String) -> Bool

Whether the string starts with prefix (always for an empty one).

<prelude>:2171

def end_with?(suffix: String) -> Bool

Whether the string ends with suffix (always for an empty one).

<prelude>:2173

def include?(other: String) -> Bool

Whether other occurs in the string (always for an empty one).

<prelude>:2175

def index(other: String) -> Int?

The character index of the first occurrence of other, or nil when there is none.

"héllo".index("l")      # => 2
"héllo".index("z")      # => nil

<prelude>:2183

def rindex(other: String) -> Int?

The character index of the last occurrence of other, or nil when there is none.

<prelude>:2186

def center(width: Int, pad: String = …) -> String

The string centered in width characters, padded on both sides with pad repeated (the right side takes the odd one); the string itself when it is already as wide.

"ab".center(6, "*")     # => "**ab**"
"a".center(4)           # => " a  "

<prelude>:2195

def ljust(width: Int, pad: String = …) -> String

The string padded on the right to width characters with pad repeated; the string itself when it is already as wide.

<prelude>:2198

def rjust(width: Int, pad: String = …) -> String

The string padded on the left to width characters with pad repeated; the string itself when it is already as wide.

"7".rjust(3, "0")       # => "007"

<prelude>:2205

def tr(from: String, to: String) -> String

The string with each character of from replaced by the character at the same place in to, the last one of to standing for those past its end. Both may hold ranges ("a-y"), and a from starting with ^ means every character not in it. An empty to deletes them.

"hello".tr("el", "ip")    # => "hippo"
"hello".tr("a-y", "b-z")  # => "ifmmp"
"hello".tr("^l", "*")     # => "**ll*"

<prelude>:2216

def delete(chars: String) -> String

The string without the characters in chars, a set written as #tr's from (ranges, ^ for the complement).

"hello".delete("l")     # => "heo"

<prelude>:2223

def squeeze -> String

The string with each run of the same character made one.

"aaabbb  c".squeeze     # => "ab c"

<prelude>:2229

def count(chars: String) -> Int

The number of characters in the string that are in chars, a set written as #tr's from.

"hello world".count("lo")   # => 5

<prelude>:2236

def reverse -> String

The characters in reverse order (a combining mark is a character of its own here).

<prelude>:2239

def each_char(&: (String) -> Void) -> Void

Calls the block with each character.

<prelude>:2241

def each_line(&: (String) -> Void) -> Void

Calls the block with each line, as #lines gives them.

<prelude>:2243

def to_i -> Int

The integer at the start of the string, in base 10, as Ruby reads it: leading whitespace, a sign and a 0d prefix are allowed, a single _ may stand between digits ("1_000"; "1__2" is 1), and the first other character ends it. 0 when there is no digit.

Raises

OverflowError when the number does not fit in an Int.

"  42abc".to_i          # => 42
"1_000".to_i            # => 1000
"abc".to_i              # => 0

<prelude>:2258

def to_i(base: Int) -> Int

The integer at the start of the string in base (2 to 36, or 0), read as #to_i reads it. As in Ruby, the prefix naming base is skipped (0x for 16, 0b for 2, 0o for 8, 0d for 10, in either case), and base 0 takes the base from the prefix: octal for a bare leading 0, decimal without one.

Raises

OverflowError when the number does not fit in an Int, ArgumentError for a base that is not 0 or within 2..36.

"ff".to_i(16)           # => 255
"0xff".to_i(16)         # => 255
"1012".to_i(2)          # => 5
"0b101".to_i(0)         # => 5
"017".to_i(0)           # => 15
"0x1f".to_i(10)         # => 0
"10".to_i(37)           # raises ArgumentError

<prelude>:2279

def to_f -> Float

The decimal number at the start of the string (leading whitespace, a sign, a fraction and an exponent); 0.0 when there is none. _ is not read, nor "Infinity" or "NaN".

" 3.5e2xyz".to_f        # => 350.0
"x".to_f                # => 0.0

<prelude>:2288

def to_sym -> Symbol

The symbol of this name.

<prelude>:2290

def to_bytes -> Bytes

The UTF-8 bytes.

"é".to_bytes            # => b"\xc3\xa9"

<prelude>:2296

def b -> Bytes

Ruby's name for the same: the UTF-8 bytes ("é".b).

<prelude>:2298

def encode(encoding: String = …) -> Bytes

The string encoded in encoding: "UTF-8", "ASCII" or "ISO-8859-1". Bytes#decode converts back.

Raises

ArgumentError for another encoding, or a character the encoding cannot hold.

"é".encode("ISO-8859-1")  # => b"\xe9"
"é".encode("ASCII")       # raises ArgumentError

<prelude>:2311

def to_s -> String

The string itself.

<prelude>:2313

def inspect -> String

The string as a literal: in double quotes, with ", \ and control characters escaped. Characters beyond ASCII are kept, and unlike Ruby's, #{ is not escaped.

"a\"b\n".inspect        # => "\"a\\\"b\\n\""

<prelude>:2321

def hash -> Int

A hash code: equal strings have equal ones.

<prelude>:2323

def succ -> String

The successor, as Ruby's: the rightmost letter or digit is incremented, carrying to the left ("az" is followed by "ba", "zz" by "aaa") across other characters ("1.9" by "2.0"), but not from a letter across them to a digit or back ("1.z" by "1.aa"); a string without one increments its last character.

"az".succ               # => "ba"
"Zz9".succ              # => "AAa0"
"1.9".succ              # => "2.0"

<prelude>:2335

def next -> String

The successor: the same as succ.

<prelude>:2337

def ord -> Int

The code point of the first character.

Raises

ArgumentError for an empty string.

"é".ord                 # => 233

<prelude>:2347

def hex -> Int

The string read as a hexadecimal number.

As Ruby's, the same as to_i(16): the number at the start, after whitespace, a sign and a 0x prefix, with a single _ allowed between digits; 0 when there is none.

Raises

OverflowError when the number does not fit in an Int.

"0x1A".hex              # => 26
"-ff".hex               # => -255
"1fg".hex               # => 31
"-0x1f".hex             # => -31
"zz".hex                # => 0

<prelude>:2365

def oct -> Int

The string read as an octal number.

As Ruby's: the number at the start, read as #to_i reads it, in the base its prefix names (0x, 0b, 0o, 0d) and in octal without one; 0 when there is none.

Raises

OverflowError when the number does not fit in an Int.

"777".oct               # => 511
"-17".oct               # => -15
"17x".oct               # => 15
"0x1f".oct              # => 31
"0b11".oct              # => 3
"19".oct                # => 1

<prelude>:2384

def %(arg: Object) -> String

The string as a format with one value, arg, as %(args) formats an array of values.

"%d items" % 3          # => "3 items"

<prelude>:2391

def [](start: Int, length: Int) -> String

The length characters from character index start (from the end when negative); fewer at the end of the string, and empty when start is the size.

Raises

IndexError when start is out of range or length is negative.

"héllo"[1, 2]           # => "él"
"héllo"[-2, 5]          # => "lo"

<prelude>:2404

def [](pattern: Regexp) -> String?

The text of the first match of pattern, or nil when there is none.

"héllo"[/l+/]           # => "ll"
"héllo"[/z/]            # => nil

<prelude>:2412

def slice(start: Int, length: Int) -> String

The same as self[start, length].

<prelude>:2414

def slice(range: Range[Int]) -> String

The same as self[range].

<prelude>:2416

def codepoints -> Array[Int]

The code point of each character.

<prelude>:2418

def getbyte(index: Int) -> Int?

The byte at byte index index (from the end when negative), or nil when it is out of range.

"é".getbyte(0)          # => 195
"é".getbyte(2)          # => nil

<prelude>:2426

def each_byte(&: (Int) -> Void) -> Void

Calls the block with each byte of the UTF-8 encoding.

<prelude>:2428

def each_char -> Enumerator[String]

An enumerator of the characters.

<prelude>:2430

def graphemes -> Array[String]

The extended grapheme clusters: what a reader sees as one character, a base with its combining marks, an emoji sequence.

"éx".chars.size      # => 3
"éx".graphemes.size  # => 2

<prelude>:2438

def each_grapheme(&: (String) -> Void) -> Void

Calls the block with each grapheme cluster, as #graphemes gives them.

<prelude>:2441

def lines(chomp: Bool) -> Array[String]

The lines, without their line ending when chomp is true.

"a\nb\r\nc\n".lines(chomp: true)   # => ["a", "b", "c"]

<prelude>:2447

def split(separator: String, limit: Int) -> Array[String]

The fields separated by separator, at most limit of them when it is positive (the last holds the rest). A negative limit keeps the empty fields at the end; 0 is as no limit.

"a,b,c".split(",", 2)    # => ["a", "b,c"]
"a,b,,".split(",", -1)   # => ["a", "b", "", ""]

<prelude>:2456

def split(separator: Regexp, limit: Int) -> Array[String]

The fields separated by matches of separator, with limit as split(String, Int) reads it.

<prelude>:2459

def partition(separator: String) -> [String, String, String]

The text before the first occurrence of separator, the separator, and the text after it; the string and two empty strings when there is none.

"a=b=c".partition("=")  # => ["a", "=", "b=c"]
"abc".partition("=")    # => ["abc", "", ""]

<prelude>:2468

def partition(pattern: Regexp) -> [String, String, String]

The text before the first match of pattern, the match, and the text after it; the string and two empty strings when there is none.

<prelude>:2471

def rpartition(separator: String) -> [String, String, String]

The text before the last occurrence of separator, the separator, and the text after it; two empty strings and the string when there is none.

"a=b=c".rpartition("=")  # => ["a=b", "=", "c"]
"abc".rpartition("=")    # => ["", "", "abc"]

<prelude>:2480

def rpartition(pattern: Regexp) -> [String, String, String]

The text before the last match of pattern (the last position a match starts at), the match, and the text after it; two empty strings and the string when there is none.

<prelude>:2484

def delete_prefix(prefix: String) -> String

The string without prefix at its start; the string itself when it does not start with it.

<prelude>:2487

def delete_suffix(suffix: String) -> String

The string without suffix at its end; the string itself when it does not end with it.

<prelude>:2490

def casecmp?(other: String) -> Bool

Whether the strings are equal ignoring case (Unicode case folding).

"HÉllo".casecmp?("héLLO")   # => true

<prelude>:2496

def casecmp(other: String) -> Int

Compares as <=> does after folding case (Unicode): -1, 0 or 1.

<prelude>:2498

def insert(index: Int, other: String) -> String

The string with other inserted before character index index. A negative index counts from the end, so that -1 appends.

Raises

IndexError when index is beyond the size.

"héllo".insert(1, "X")   # => "hXéllo"
"héllo".insert(-1, "X")  # => "hélloX"

<prelude>:2510

def prepend(other: String) -> String

The string with other in front of it.

<prelude>:2512

def ascii_only? -> Bool

Whether every character is ASCII.

<prelude>:2514

def upto(last: String, &: (String) -> Void) -> Void

Calls the block with the strings from this one to last, one at a time, as Ruby steps them: two single ASCII characters by character; two strings of digits as numbers of any size, padded to this one's width ("9".upto("10") gives "9" and "10"); otherwise this string and each #succ after it, up to last or until one is longer than last in bytes or is last.succ. Nothing is yielded when this string sorts after last ("c".upto("a"), "b".upto("aa")).

r: Array[String] = []
"a8".upto("b1") { |s| r = r.push(s) }
r                       # => ["a8", "a9", "b0", "b1"]

<prelude>:2528

def squeeze(chars: String) -> String

The string with each run of the same character made one, for the characters in chars only (a set written as #tr's from).

"aaabbbccc".squeeze("a-b")  # => "abccc"

<prelude>:2535

def chomp(suffix: String) -> String

The string without suffix at its end; the string itself when it does not end with it. Unlike Ruby's, an empty suffix removes nothing.

<prelude>:2539

def start_with?(first: String, second: String, *rest: String) -> Bool

Whether the string starts with any of the prefixes given.

<prelude>:2541

def start_with?(pattern: Regexp) -> Bool

Whether pattern matches at the start of the string.

"hello".start_with?(/h.l/)  # => true
"xhello".start_with?(/h/)   # => false

<prelude>:2548

def end_with?(first: String, second: String, *rest: String) -> Bool

Whether the string ends with any of the suffixes given.

<prelude>:2550

def index(other: String, start: Int) -> Int?

The character index of the first occurrence of other at or after character index start (from the end when negative), or nil when there is none.

<prelude>:2554

def index(pattern: Regexp) -> Int?

The character index of the first match of pattern, or nil when there is none.

<prelude>:2557

def index(pattern: Regexp, start: Int) -> Int?

The character index of the first match of pattern at or after character index start (from the end when negative), or nil when there is none.

<prelude>:2561

def rindex(other: String, start: Int) -> Int?

The character index of the last occurrence of other that starts at or before character index start (from the end when negative), or nil when there is none.

<prelude>:2565

def rindex(pattern: Regexp) -> Int?

The character index of the last position a match of pattern starts at, or nil when there is none.

<prelude>:2568

def rindex(pattern: Regexp, start: Int) -> Int?

The character index of the last position at or before character index start where a match of pattern starts, or nil when there is none.

<prelude>:2572

def sub(pattern: String, &: (String) -> String) -> String

The string with the first occurrence of pattern replaced by what the block returns for it; the block receives the matched text.

<prelude>:2575

def sub(pattern: Regexp, &: (String) -> String) -> String

The string with the first match of pattern replaced by what the block returns for the matched text.

<prelude>:2578

def sub(pattern: Regexp, &: (String, MatchData) -> String) -> String

The string with the first match of pattern replaced by what the block returns; the block receives the matched text and its MatchData, since there is no $~.

"a1b2".sub(/(\w)(\d)/) { |s, m| "#{m[2]}#{m[1]}" }   # => "1ab2"

<prelude>:2586

def gsub(pattern: String, &: (String) -> String) -> String

The string with every occurrence of pattern replaced by what the block returns for it; the block receives the matched text.

"abcb".gsub("b") { |s| s.upcase }   # => "aBcB"

<prelude>:2593

def gsub(pattern: Regexp, &: (String) -> String) -> String

The string with every match of pattern replaced by what the block returns for the matched text.

<prelude>:2596

def gsub(pattern: Regexp, &: (String, MatchData) -> String) -> String

The string with every match of pattern replaced by what the block returns; the block receives the matched text and its MatchData.

"a=1 b=2".gsub(/(\w)=(\w)/) { |s, m| "#{m[2]}=#{m[1]}" }
# => "1=a 2=b"

<prelude>:2604

def gsub(pattern: Regexp, replacements: Hash[String, String]) -> String

The string with every match of pattern replaced by the value of the matched text in replacements; a text that is not a key is removed.

"cat hat".gsub(/[ch]/, {"c" => "b", "h" => "m"})   # => "bat mat"

<prelude>:2612

def scan(pattern: Regexp, &: (String) -> Void) -> Void

Calls the block with the text of every match of pattern.

<prelude>:2614

def scan(pattern: Regexp, &: (String, MatchData) -> Void) -> Void

Calls the block with the text and the MatchData of every match of pattern, for its groups.

<prelude>:2617