On this page
- Substitution Methods
- Whitespace in Strings
- String Slices
- What’s Here
- Methods for Creating a String
- Methods for a Frozen/Unfrozen String
- Methods for Querying
- Methods for Comparing
- Methods for Modifying a String
- Methods for Converting to New String
- Methods for Converting to Non-String
- Methods for Iterating
- Class methods
- Instance methods
- Ruby version changes
Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
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:
String Slices
A slice of a string is a substring selected by certain criteria.
These instance methods utilize slicing:
-
String#[](aliased asString#slice): Returns a slice copied fromself. -
String#[]=: Mutatesselfwith the slice replaced. -
String#slice!: Mutatesselfwith the slice removed and returns the removed slice.
Each of the above methods takes arguments that determine the slice to be copied or replaced.
The arguments have several forms. For a string string, the forms are:
-
string[index] -
string[start, length] -
string[range] -
string[regexp, capture = 0] -
string[substring]
string[index]
When a non-negative integer argument index is given, the slice is the 1-character substring found in self at character offset index:
'bar'[0] # => "b" 'bar'[2] # => "r" 'bar'[20] # => nil 'тест'[2] # => "с" 'こんにちは'[4] # => "は"
When a negative integer index is given, the slice begins at the offset given by counting backward from the end of self:
'bar'[-3] # => "b" 'bar'[-1] # => "r" 'bar'[-20] # => nil
string[start, length]
When non-negative integer arguments start and length are given, the slice begins at character offset start, if it exists, and continues for length characters, if available:
'foo'[0, 2] # => "fo" 'тест'[1, 2] # => "ес" 'こんにちは'[2, 2] # => "にち" # Zero length. 'foo'[2, 0] # => "" # Length not entirely available. 'foo'[1, 200] # => "oo" # Start out of range. 'foo'[4, 2] # => nil
Special case: if start equals the length of self, the slice is a new empty string:
'foo'[3, 2] # => "" 'foo'[3, 200] # => ""
When a negative start and non-negative length are given, the slice begins by counting backward from the end of self, and continues for length characters, if available:
'foo'[-2, 2] # => "oo" 'foo'[-2, 200] # => "oo" # Start out of range. 'foo'[-4, 2] # => nil
When a negative length is given, there is no slice:
'foo'[1, -1] # => nil 'foo'[-2, -1] # => nil
string[range]
When a Range argument range is given, it creates a substring of string using the indices in range. The slice is then determined as above:
'foo'[0..1] # => "fo" 'foo'[0, 2] # => "fo" 'foo'[2...2] # => "" 'foo'[2, 0] # => "" 'foo'[1..200] # => "oo" 'foo'[1, 200] # => "oo" 'foo'[4..5] # => nil 'foo'[4, 2] # => nil 'foo'[-4..-3] # => nil 'foo'[-4, 2] # => nil 'foo'[3..4] # => "" 'foo'[3, 2] # => "" 'foo'[-2..-1] # => "oo" 'foo'[-2, 2] # => "oo" 'foo'[-2..197] # => "oo" 'foo'[-2, 200] # => "oo"
string[regexp, capture = 0]
When the Regexp argument regexp is given, and the capture argument is 0, the slice is the first matching substring found in self:
'foo'[/o/] # => "o" 'foo'[/x/] # => nil s = 'hello there' s[/[aeiou](.)\1/] # => "ell" s[/[aeiou](.)\1/, 0] # => "ell"
If the argument capture is provided and not 0, it should be either a capture group index (integer) or a capture group name (String or Symbol); the slice is the specified capture (see Groups at Regexp and Captures):
s = 'hello there' s[/[aeiou](.)\1/, 1] # => "l" s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] # => "l" s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, :vowel] # => "e"
If an invalid capture group index is given, there is no slice. If an invalid capture group name is given, IndexError is raised.
string[substring]
When the single String argument substring is given, it returns the substring from self if found, otherwise nil:
'foo'['oo'] # => "oo" 'foo'['xx'] # => nil
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:
Methods for Creating a String
-
::new: Returns a new string. -
::try_convert: Returns a new string created from a given object.
Methods for a Frozen/Unfrozen String
-
+@: 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.
Methods for Querying
Counts
-
length(aliased assize): Returns the count of characters (not bytes). -
empty?: Returnstrueifself.lengthis zero;falseotherwise. -
bytesize: Returns the count of bytes. -
count: Returns the count of substrings matching given strings.
Substrings
-
=~: Returns the index of the first substring that matches a givenRegexpor other object; returnsnilif no match is found. -
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.
Methods for 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 as a given other string is smaller than, equal to, or larger thanself. -
casecmp?: Returnstrueif the string is equal to a given string after Unicode case folding;falseotherwise.
Methods for Modifying a String
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.
Substitution
-
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. -
initialize_copy(aliased asreplace): 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. -
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.
Methods for 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 ofselfcentered between pad substrings. -
concat: Returns the concatenation ofselfwith given other strings. -
prepend: Returns the concatenation of a given other string withself. -
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 copy ofselfwith all non-printing characters replaced by \xHH notation and all special characters escaped. -
undump: Returns a copy ofselfwith all\xNNnotations replaced by\uNNNNnotations and all escaped characters unescaped. -
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.
Methods for 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_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.
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.
Methods for 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 2
Instance methods 135
Ruby version changes 10
-
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]
-