On this page
String
A String object has an arbitrary sequence of bytes, typically representing text or binary data. A String object may be created using String::new or as literals.
String objects differ from Symbol objects in that Symbol objects are designed to be used as identifiers, instead of text or data.
You can create a String object explicitly with:
You can convert certain objects to Strings with:
-
Method
String.
Some String methods modify self. Typically, a method whose name ends with ! modifies self and returns self; often, a similarly named method (without the !) returns a new string.
In general, if both bang and non-bang versions of a method exist, the bang method mutates and the non-bang method does not. However, a method without a bang can also mutate, such as String#replace.
Substitution Methods
These methods perform substitutions:
-
String#sub: One substitution (or none); returns a new string. -
String#sub!: One substitution (or none); returnsselfif any changes,nilotherwise. -
String#gsub: Zero or more substitutions; returns a new string. -
String#gsub!: Zero or more substitutions; returnsselfif any changes,nilotherwise.
Each of these methods takes:
-
A first argument,
pattern(StringorRegexp), that specifies the substring(s) to be replaced. -
Either of the following:
The examples in this section mostly use the String#sub and String#gsub methods; the principles illustrated apply to all four substitution methods.
Argument pattern
Argument pattern is commonly a regular expression:
s = 'hello' s.sub(/[aeiou]/, '*') # => "h*llo" s.gsub(/[aeiou]/, '*') # => "h*ll*" s.gsub(/[aeiou]/, '') # => "hll" s.sub(/ell/, 'al') # => "halo" s.gsub(/xyzzy/, '*') # => "hello" 'THX1138'.gsub(/\d+/, '00') # => "THX00"
When pattern is a string, all its characters are treated as ordinary characters (not as Regexp special characters):
'THX1138'.gsub('\d+', '00') # => "THX1138"
String replacement
If replacement is a string, that string determines the replacing string that is substituted for the matched text.
Each of the examples above uses a simple string as the replacing string.
String replacement may contain back-references to the pattern’s captures:
-
\n(n is a non-negative integer) refers to$n. -
\k<name>refers to the named capturename.
See Regexp for details.
Note that within the string replacement, a character combination such as $& is treated as ordinary text, not as a special match variable. However, you may refer to some special match variables using these combinations:
-
\&and\0correspond to$&, which contains the complete matched text. -
\'corresponds to$', which contains the string after the match. -
`corresponds to$`, which contains the string before the match. -
\+corresponds to$+, which contains the last capture group.
See Regexp for details.
Note that \\ is interpreted as an escape, i.e., a single backslash.
Note also that a string literal consumes backslashes. See String Literals for details about string literals.
A back-reference is typically preceded by an additional backslash. For example, if you want to write a back-reference \& in replacement with a double-quoted string literal, you need to write "..\\&..".
If you want to write a non-back-reference string \& in replacement, you need to first escape the backslash to prevent this method from interpreting it as a back-reference, and then you need to escape the backslashes again to prevent a string literal from consuming them: "..\\\\&..".
You may want to use the block form to avoid excessive backslashes.
Hash replacement
If the argument replacement is a hash, and pattern matches one of its keys, the replacing string is the value for that key:
h = {'foo' => 'bar', 'baz' => 'bat'} 'food'.sub('foo', h) # => "bard"
Note that a symbol key does not match:
h = {foo: 'bar', baz: 'bat'} 'food'.sub('foo', h) # => "d"
Block
In the block form, the current match string is passed to the block; the block’s return value becomes the replacing string:
s = '@' '1234'.gsub(/\d/) { |match| s.succ! } # => "ABCD"
Special match variables such as $1, $2, $`, $&, and $' are set appropriately.
Whitespace in Strings
In the class String, whitespace is defined as a contiguous sequence of characters consisting of any mixture of the following:
-
NL (null):
"\x00","\u0000". -
HT (horizontal tab):
"\x09","\t". -
LF (line feed):
"\x0a","\n". -
VT (vertical tab):
"\x0b","\v". -
FF (form feed):
"\x0c","\f". -
CR (carriage return):
"\x0d","\r". -
SP (space):
"\x20"," ".
Whitespace is relevant for the following methods:
What’s Here
First, what’s elsewhere. Class String:
-
Inherits from the Object class.
-
Includes the Comparable module.
Here, class String provides methods that are useful for:
Creating a String
-
::new: Returns a new string. -
::try_convert: Returns a new string created from a given object.
Freezing/Unfreezing
-
+@: Returns a string that is not frozen:selfif not frozen;self.dupotherwise. -
-@(aliased asdedup): Returns a string that is frozen:selfif already frozen;self.freezeotherwise. -
freeze: Freezesselfif not already frozen; returnsself.
Querying
Counts
-
bytesize: Returns the count of bytes. -
count: Returns the count of substrings matching given strings. -
empty?: Returns whether the length ofselfis zero. -
length(aliased assize): Returns the count of characters (not bytes).
Substrings
-
=~: Returns the index of the first substring that matches a givenRegexpor other object; returnsnilif no match is found. -
byteindex: Returns the byte index of the first occurrence of a given substring. -
byterindex: Returns the byte index of the last occurrence of a given substring. -
index: Returns the index of the first occurrence of a given substring; returnsnilif none found. -
rindex: Returns the index of the last occurrence of a given substring; returnsnilif none found. -
include?: Returnstrueif the string contains a given substring;falseotherwise. -
match: Returns aMatchDataobject if the string matches a givenRegexp;nilotherwise. -
match?: Returnstrueif the string matches a givenRegexp;falseotherwise. -
start_with?: Returnstrueif the string begins with any of the given substrings. -
end_with?: Returnstrueif the string ends with any of the given substrings.
Encodings
-
encoding: Returns theEncodingobject that represents the encoding of the string. -
unicode_normalized?: Returnstrueif the string is in Unicode normalized form;falseotherwise. -
valid_encoding?: Returnstrueif the string contains only characters that are valid for its encoding. -
ascii_only?: Returnstrueif the string has only ASCII characters;falseotherwise.
Other
-
sum: Returns a basic checksum for the string: the sum of each byte. -
hash: Returns the integer hash code.
Comparing
-
==(aliased as===): Returnstrueif a given other string has the same content asself. -
eql?: Returnstrueif the content is the same as the given other string. -
<=>: Returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger thanself. -
casecmp: Ignoring case, returns -1, 0, or 1 asselfis smaller than, equal to, or larger than a given other string. -
casecmp?: Ignoring case, returns whether a given other string is equal toself.
Modifying
Each of these methods modifies self.
Insertion
-
insert: Returnsselfwith a given string inserted at a specified offset. -
<<: Returnsselfconcatenated with a given string or integer. -
append_as_bytes: Returnsselfconcatenated with strings without performing any encoding validation or conversion. -
prepend: Prefixes toselfthe concatenation of given other strings.
Substitution
-
bytesplice: Replaces bytes ofselfwith bytes from a given string; returnsself. -
sub!: Replaces the first substring that matches a given pattern with a given replacement string; returnsselfif any changes,nilotherwise. -
gsub!: Replaces each substring that matches a given pattern with a given replacement string; returnsselfif any changes,nilotherwise. -
succ!(aliased asnext!): Returnsselfmodified to become its own successor. -
replace: Returnsselfwith its entire content replaced by a given string. -
reverse!: Returnsselfwith its characters in reverse order. -
setbyte: Sets the byte at a given integer offset to a given value; returns the argument. -
tr!: Replaces specified characters inselfwith specified replacement characters; returnsselfif any changes,nilotherwise. -
tr_s!: Replaces specified characters inselfwith specified replacement characters, removing duplicates from the substrings that were modified; returnsselfif any changes,nilotherwise.
Casing
-
capitalize!: Upcases the initial character and downcases all others; returnsselfif any changes,nilotherwise. -
downcase!: Downcases all characters; returnsselfif any changes,nilotherwise. -
upcase!: Upcases all characters; returnsselfif any changes,nilotherwise. -
swapcase!: Upcases each downcase character and downcases each upcase character; returnsselfif any changes,nilotherwise.
Encoding
-
encode!: Returnsselfwith all characters transcoded from one encoding to another. -
unicode_normalize!: Unicode-normalizesself; returnsself. -
scrub!: Replaces each invalid byte with a given character; returnsself. -
force_encoding: Changes the encoding to a given encoding; returnsself.
Deletion
-
clear: Removes all content, so thatselfis empty; returnsself. -
slice!,[]=: Removes a substring determined by a given index, start/length, range, regexp, or substring. -
squeeze!: Removes contiguous duplicate characters; returnsself. -
delete!: Removes characters as determined by the intersection of substring arguments. -
delete_prefix!: Removes leading prefix; returnsselfif any changes,nilotherwise. -
delete_suffix!: Removes trailing suffix; returnsselfif any changes,nilotherwise. -
lstrip!: Removes leading whitespace; returnsselfif any changes,nilotherwise. -
rstrip!: Removes trailing whitespace; returnsselfif any changes,nilotherwise. -
strip!: Removes leading and trailing whitespace; returnsselfif any changes,nilotherwise. -
chomp!: Removes the trailing record separator, if found; returnsselfif any changes,nilotherwise. -
chop!: Removes trailing newline characters if found; otherwise removes the last character; returnsselfif any changes,nilotherwise.
Converting to New String
Each of these methods returns a new String based on self, often just a modified copy of self.
Extension
-
*: Returns the concatenation of multiple copies ofself. -
+: Returns the concatenation ofselfand a given other string. -
center: Returns a copy ofself, centered by specified padding. -
concat: Returns the concatenation ofselfwith given other strings. -
ljust: Returns a copy ofselfof a given length, right-padded with a given other string. -
rjust: Returns a copy ofselfof a given length, left-padded with a given other string.
Encoding
-
b: Returns a copy ofselfwith ASCII-8BIT encoding. -
scrub: Returns a copy ofselfwith each invalid byte replaced with a given character. -
unicode_normalize: Returns a copy ofselfwith each character Unicode-normalized. -
encode: Returns a copy ofselfwith all characters transcoded from one encoding to another.
Substitution
-
dump: Returns a printable version ofself, enclosed in double-quotes. -
undump: Inverse ofdump; returns a copy ofselfwith changes of the kinds made bydump“undone.” -
sub: Returns a copy ofselfwith the first substring matching a given pattern replaced with a given replacement string. -
gsub: Returns a copy ofselfwith each substring that matches a given pattern replaced with a given replacement string. -
succ(aliased asnext): Returns the string that is the successor toself. -
reverse: Returns a copy ofselfwith its characters in reverse order. -
tr: Returns a copy ofselfwith specified characters replaced with specified replacement characters. -
tr_s: Returns a copy ofselfwith specified characters replaced with specified replacement characters, removing duplicates from the substrings that were modified. -
%: Returns the string resulting from formatting a given object intoself.
Casing
-
capitalize: Returns a copy ofselfwith the first character upcased and all other characters downcased. -
downcase: Returns a copy ofselfwith all characters downcased. -
upcase: Returns a copy ofselfwith all characters upcased. -
swapcase: Returns a copy ofselfwith all upcase characters downcased and all downcase characters upcased.
Deletion
-
delete: Returns a copy ofselfwith characters removed. -
delete_prefix: Returns a copy ofselfwith a given prefix removed. -
delete_suffix: Returns a copy ofselfwith a given suffix removed. -
lstrip: Returns a copy ofselfwith leading whitespace removed. -
rstrip: Returns a copy ofselfwith trailing whitespace removed. -
strip: Returns a copy ofselfwith leading and trailing whitespace removed. -
chomp: Returns a copy ofselfwith a trailing record separator removed, if found. -
chop: Returns a copy ofselfwith trailing newline characters or the last character removed. -
squeeze: Returns a copy ofselfwith contiguous duplicate characters removed. -
[](aliased asslice): Returns a substring determined by a given index, start/length, range, regexp, or string. -
byteslice: Returns a substring determined by a given index, start/length, or range. -
chr: Returns the first character.
Duplication
-
to_s(aliased asto_str): Ifselfis a subclass ofString, returnsselfcopied into aString; otherwise, returnsself.
Converting to Non-String
Each of these methods converts the contents of self to a non-String.
Characters, Bytes, and Clusters
-
bytes: Returns an array of the bytes inself. -
chars: Returns an array of the characters inself. -
codepoints: Returns an array of the integer ordinals inself. -
getbyte: Returns the integer byte at the given index inself. -
grapheme_clusters: Returns an array of the grapheme clusters inself.
Splitting
-
lines: Returns an array of the lines inself, as determined by a given record separator. -
partition: Returns a 3-element array determined by the first substring that matches a given substring or regexp. -
rpartition: Returns a 3-element array determined by the last substring that matches a given substring or regexp. -
split: Returns an array of substrings determined by a given delimiter – regexp or string – or, if a block is given, passes those substrings to the block.
Matching
-
scan: Returns an array of substrings matching a given regexp or string, or, if a block is given, passes each matching substring to the block. -
unpack: Returns an array of substrings extracted fromselfaccording to a given format. -
unpack1: Returns the first substring extracted fromselfaccording to a given format.
Numerics
-
hex: Returns the integer value of the leading characters, interpreted as hexadecimal digits. -
oct: Returns the integer value of the leading characters, interpreted as octal digits. -
ord: Returns the integer ordinal of the first character inself. -
to_c: Returns the complex value of leading characters, interpreted as a complex number. -
to_i: Returns the integer value of leading characters, interpreted as an integer. -
to_f: Returns the floating-point value of leading characters, interpreted as a floating-point number. -
to_r: Returns the rational value of leading characters, interpreted as a rational.
Strings and Symbols
-
inspect: Returns a copy ofself, enclosed in double quotes, with special characters escaped. -
intern(aliased asto_sym): Returns the symbol corresponding toself.
Iterating
-
each_byte: Calls the given block with each successive byte inself. -
each_char: Calls the given block with each successive character inself. -
each_codepoint: Calls the given block with each successive integer codepoint inself. -
each_grapheme_cluster: Calls the given block with each successive grapheme cluster inself. -
each_line: Calls the given block with each successive line inself, as determined by a given record separator. -
upto: Calls the given block with each string value returned by successive calls tosucc.
Class methods 3
Instance methods 137
Ruby version changes 12
-
4.0
-
Update Unicode to Version 17.0.0 and Emoji Version 17.0. [Feature #19908][Feature #20724][Feature #21275] (also applies to
Regexp) -
String#strip,strip!,lstrip,lstrip!,rstrip, andrstrip!are extended to accept*selectorsarguments. [Feature #21552]
-
-
3.4
-
String#append_as_byteswas added to more easily and efficiently work with binary buffers and protocols. It directly concatenate the arguments into the string without any encoding validation or conversion. [Feature #20594]
-
-
3.3
-
String#unpacknow raisesArgumentErrorfor unknown directives. [Bug #19150] -
String#bytesplicenow accepts new arguments index/length or range of the source string to be copied. [Feature #19314]
-
-
3.2
-
String#byteindexandString#byterindexhave been added. [Feature #13110] -
Update Unicode to Version 15.0.0 and Emoji Version 15.0. [Feature #18639] (also applies to
Regexp) -
String#bytesplicehas been added. [Feature #18598] -
String#deduphas been added as an alias toString#-@. [Feature #18595]
-
-
3.1
-
Update Unicode version to 13.0.0 [Feature #17750] and Emoji version to 13.0 [Feature #18029]
-
String#unpackandString#unpack1now accept anoffset:keyword argument to start the unpacking after an arbitrary number of bytes have been skipped. Ifoffsetis outside of the string boundsArgumentErroris raised. [Feature #18254]
-
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-