Skip to content

Strings ​

Strings are immutable: every function returns a new string. Indexes and lengths are in characters, not bytes.

mzs
"привет".len  # → 6
"привет".bytes.len  # → 12
"привет"[0]  # → "п"
"привет"[-1]  # → "т"
"ab" + "cd"  # → "abcd"
"-" * 3  # → "---"

Case ​

FunctionWhat it does
lower / upperlower / upper case
capitalizefirst letter upper case, the rest lower
swapcaseflips the case of each letter
casefolda key for case-insensitive comparison
mzs
"ПРИВЕТ".lower  # → "привет"
"Ёлка".upper  # → "ЁЛКА"
"HELLO world".capitalize  # → "Hello world"
"aBc".swapcase  # → "AbC"
"Straße".casefold == "STRASSE".casefold  # → true

Trimming ​

FunctionWhat it does
trim / trim_start / trim_endwhitespace at both ends / the start / the end
trim(chars)the given characters instead of whitespace
chomp(suffix = "\n")removes one newline or the suffix
chopremoves the last character
squeeze(chars = "")collapses runs of repeated characters
mzs
"  OPERATOR  ".trim  # → "OPERATOR"
"  x  ".trim_end  # → "  x"
"-=a=-".trim("=-")  # → "a"
"file.txt".chomp(".txt")  # → "file"
"abc".chop  # → "ab"
"aa  bb".squeeze(" ")  # → "aa bb"

Checks ​

FunctionWhat it does
lennumber of characters
widthwidth in terminal columns (CJK and emoji count as two)
empty / blankempty / empty after trim
has(sub)whether the substring is there
starts_with(*p) / ends_with(*s)starts / ends with any of the options
mzs
"日本".width  # → 4
" ".empty  # → false
" ".blank  # → true
"hello".has("lo")  # → true
"/start".starts_with("/", "!")  # → true
"a.png".ends_with(".jpg", ".png")  # → true
"llo" in "hello"  # → true

For a regex, use the ~ operator: "abc" ~ /b/. has takes only a string.

FunctionWhat it does
index(needle, from = 0)position of the first occurrence, or nil
last_index(needle)position of the last one
count(sub)number of occurrences
matches(re)all matches; with groups, arrays of groups
captures(re)the match and its groups, or nil

needle and sub are a string or a regex. A string is matched literally.

mzs
"привет".index("вет")  # → 3
"привет".index(/ВЕТ/i)  # → 3
"abcabc".index("b", 2)  # → 4
"abc".index("z")  # → nil
"abcabc".last_index("b")  # → 4
"a1b22".count(/\d/)  # → 3
"a1 b2".matches(/[a-z]\d/)  # → ["a1","b2"]
"a1 b2".matches(/([a-z])(\d)/)  # → [["a","1"],["b","2"]]
"2024-05".captures(/(\d+)-(\d+)/)  # → ["2024-05","2024","05"]
"2024-05".captures(/(?P<y>\d+)/)["y"]  # → "2024"
"none".captures(/\d/)  # → nil

Splitting ​

FunctionWhat it does
split(sep = " ", limit = -1)by a string or a regex; " " splits on any whitespace
linesinto lines, \r\n too
charsan array of characters
bytesan array of bytes
mzs
"a:b:c".split(":")  # → ["a","b","c"]
"a b  c".split  # → ["a","b","c"]
"a:b:c".split(":", 2)  # → ["a","b:c"]
"a1b2".split(/\d/)  # → ["a","b",""]
"a\r\nb\n".lines  # → ["a","b"]
"да".chars  # → ["д","а"]
"я".bytes  # → [209,143]
"да".chars.join("-")  # → "д-а"

Replacing ​

FunctionWhat it does
replace(pat, repl)replaces all occurrences
replace_first(pat, repl)only the first

pat is a string or a regex. repl is a string (\1, \k<name> are groups; write it in single quotes) or a closure: it gets the match and the groups.

mzs
"a-b-a".replace("a", "X")  # → "X-b-X"
"a-b-a".replace_first("a", "X")  # → "X-b-a"
"+7 (999) 123-45-67".replace(/\D/, "")  # → "79991234567"
"John Smith".replace(/(\w+) (\w+)/, '\2, \1')  # → "Smith, John"
"a1b2".replace(/\d/) { it.int + 1 }  # → "a2b3"
"ab cd".replace(/(\w)(\w)/) { (_, a, b) -> b + a }  # → "ba dc"

Slices ​

FunctionWhat it does
first(n = 1) / last(n = 1)the first / last n characters
take(n) / drop(n)the first n / everything after them
slice(i, n = 1)n characters from position i (same as s[i, n])
reversereversed
mzs
"привет".first(2)  # → "пр"
"привет".last(2)  # → "ет"
"привет".drop(2)  # → "ивет"
"привет".slice(1, 3)  # → "рив"
"привет"[1, 3]  # → "рив"
"привет"[1..3]  # → "рив"
"abc".slice(9)  # → nil
"привет".reverse  # → "тевирп"

Padding and wrapping ​

Width is counted in columns, so tables with emoji and CJK line up.

FunctionWhat it does
ljust(w, pad = " ") / rjust / centerpads to width w
truncate(w, tail = "…")cuts to w columns with a tail
wrap(w)wraps at words, returns an array of lines
indent(prefix)a prefix before each non-empty line
mzs
"Ivan".ljust(8, ".")  # → "Ivan...."
"42".rjust(5)  # → "   42"
"ab".center(7, "-")  # → "--ab---"
"hello world".truncate(8)  # → "hello w…"
"hello world".truncate(8, "...")  # → "hello..."
"the quick brown fox jumps".wrap(10)  # → ["the quick","brown fox","jumps"]
"a\n\nb".indent("> ")  # → "> a\n\n> b"

Conversion ​

FunctionWhat it does
int / floatthe leading number, never fails
parse_int(base = 10) / parse_floatthe whole string as a number, or nil
ordcode of the first character (the reverse is n.chr)
jsonthe string in JSON quotes
s % argsformat with the string as the template
mzs
"12abc".int  # → 12
"12abc".parse_int  # → nil
"Я".ord  # → 1071
1071.chr  # → "Я"
"%d%%" % [50]  # → "50%"
"%s: %.2f" % ["total", 3.14159]  # → "total: 3.14"

Iterating ​

each_char { … } calls the closure for each character and returns the string.

mzs
"abc".each_char { print(it.upper) }
println()
text
ABC