On this page
- Substitution Methods
- 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
End of Life Ruby 3.1 has reached end of life and gets no more fixes. 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 there exist both bang and non-bang version of method, the bang! mutates and the non-bang! 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); returnsself. -
String#gsub: Zero or more substitutions; returns a new string. -
String#gsub!: Zero or more substitutions; returnsself.
Each of these methods takes:
-
A first argument,
pattern(string or regexp), that specifies the substring(s) to be replaced. -
Either of these:
-
A second argument,
replacement(string or hash), that determines the replacing string. -
A block that will determine the replacing string.
-
The examples in this section mostly use methods String#sub and String#gsub; 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 will determine the replacing string that is to be 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 a non-negative integer) refers to$n. -
\k<name>refers to the named capturename.
See regexp.rdoc for details.
Note that within the string replacement, a character combination such as $& is treated as ordinary text, and 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 string after match. -
`corresponds to$`, which contains string before match. -
+corresponds to$+, which contains last capture group.
See regexp.rdoc 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 first to 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 a lot of backslashes.
Hash replacement
If 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.
What’s Here
First, what’s elsewhere. Class String:
-
Inherits from class Object.
-
Includes module Comparable.
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
- #+string
-
Returns a string that is not frozen:
self, if not frozen;self.dupotherwise.
- #-string
-
Returns a string that is frozen:
self, if already frozen;self.freezeotherwise.
freeze-
Freezes
self, if not already frozen; returnsself.
Methods for Querying
Counts
empty?-
Returns
trueifself.lengthis zero;falseotherwise.
bytesize-
Returns the count of bytes.
count-
Returns the count of substrings matching given strings.
Substrings
index-
Returns the index of the first occurrence of a given substring; returns
nilif none found.
rindex-
Returns the index of the last occurrence of a given substring; returns
nilif none found.
include?-
Returns
trueif the string contains a given substring;falseotherwise.
start_with?-
Returns
trueif the string begins with any of the given substrings.
end_with?-
Returns
trueif the string ends with any of the given substrings.
Encodings
unicode_normalized?-
Returns
trueif the string is in Unicode normalized form;falseotherwise.
valid_encoding?-
Returns
trueif the string contains only characters that are valid for its encoding.
ascii_only?-
Returns
trueif 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
- #==, #===
-
Returns
trueif a given other string has the same content asself.
eql?-
Returns
trueif 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 than
self.
casecmp-
Ignoring case, returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger than
self.
casecmp?-
Returns
trueif 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-
Returns
selfwith a given string inserted at a given offset.
<<-
Returns
selfconcatenated with a given string or integer.
Substitution
sub!-
Replaces the first substring that matches a given pattern with a given replacement string; returns
selfif any changes,nilotherwise.
gsub!-
Replaces each substring that matches a given pattern with a given replacement string; returns
selfif any changes,nilotherwise.
replace-
Returns
selfwith its entire content replaced by a given string.
reverse!-
Returns
selfwith 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 in
selfwith specified replacement characters; returnsselfif any changes,nilotherwise.
tr_s!-
Replaces specified characters in
selfwith 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; returns
selfif any changes,nilotherwise.
downcase!-
Downcases all characters; returns
selfif any changes,nilotherwise.
upcase!-
Upcases all characters; returns
selfif any changes,nilotherwise.
swapcase!-
Upcases each downcase character and downcases each upcase character; returns
selfif any changes,nilotherwise.
Encoding
encode!-
Returns
selfwith all characters transcoded from one given encoding into another.
unicode_normalize!-
Unicode-normalizes
self; returnsself.
scrub!-
Replaces each invalid byte with a given character; returns
self.
force_encoding-
Changes the encoding to a given encoding; returns
self.
Deletion
clear-
Removes all content, so that
selfis empty; returnsself.
squeeze!-
Removes contiguous duplicate characters; returns
self.
delete!-
Removes characters as determined by the intersection of substring arguments.
lstrip!-
Removes leading whitespace; returns
selfif any changes,nilotherwise.
rstrip!-
Removes trailing whitespace; returns
selfif any changes,nilotherwise.
strip!-
Removes leading and trailing whitespace; returns
selfif any changes,nilotherwise.
chomp!-
Removes trailing record separator, if found; returns
selfif any changes,nilotherwise.
chop!-
Removes trailing whitespace if found, otherwise removes the last character; returns
selfif 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 of
self,
+-
Returns the concatenation of
selfand a given other string.
center-
Returns a copy of
selfcentered between pad substring.
concat-
Returns the concatenation of
selfwith given other strings.
prepend-
Returns the concatenation of a given other string with
self.
ljust-
Returns a copy of
selfof a given length, right-padded with a given other string.
rjust-
Returns a copy of
selfof a given length, left-padded with a given other string.
Encoding
b-
Returns a copy of
selfwith ASCII-8BIT encoding.
scrub-
Returns a copy of
selfwith each invalid byte replaced with a given character.
unicode_normalize-
Returns a copy of
selfwith each character Unicode-normalized.
encode-
Returns a copy of
selfwith all characters transcoded from one given encoding into another.
Substitution
dump-
Returns a copy of +self with all non-printing characters replaced by \xHH notation and all special characters escaped.
undump-
Returns a copy of +self with all
\xNNnotation replace by\uNNNNnotation and all escaped characters unescaped.
sub-
Returns a copy of
selfwith the first substring matching a given pattern replaced with a given replacement string;.
gsub-
Returns a copy of
selfwith each substring that matches a given pattern replaced with a given replacement string.
reverse-
Returns a copy of
selfwith its characters in reverse order.
tr-
Returns a copy of
selfwith specified characters replaced with specified replacement characters.
tr_s-
Returns a copy of
selfwith specified characters replaced with specified replacement characters, removing duplicates from the substrings that were modified.
%-
Returns the string resulting from formatting a given object into
self
Casing
capitalize-
Returns a copy of
selfwith the first character upcased and all other characters downcased.
downcase-
Returns a copy of
selfwith all characters downcased.
upcase-
Returns a copy of
selfwith all characters upcased.
swapcase-
Returns a copy of
selfwith all upcase characters downcased and all downcase characters upcased.
Deletion
delete-
Returns a copy of
selfwith characters removed
delete_prefix-
Returns a copy of
selfwith a given prefix removed.
delete_suffix-
Returns a copy of
selfwith a given suffix removed.
lstrip-
Returns a copy of
selfwith leading whitespace removed.
rstrip-
Returns a copy of
selfwith trailing whitespace removed.
strip-
Returns a copy of
selfwith leading and trailing whitespace removed.
chomp-
Returns a copy of
selfwith a trailing record separator removed, if found.
chop-
Returns a copy of
selfwith trailing whitespace or the last character removed.
squeeze-
Returns a copy of
selfwith contiguous duplicate characters removed.
byteslice-
Returns a substring determined by a given index, start/length, or range.
chr-
Returns the first character.
Duplication
to_s, $to_str-
If
selfis a subclass of String, returnsselfcopied into a String; 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 in
self.
chars-
Returns an array of the characters in
self.
codepoints-
Returns an array of the integer ordinals in
self.
getbyte-
Returns an integer byte as determined by a given index.
grapheme_clusters-
Returns an array of the grapheme clusters in
self.
Splitting
lines-
Returns an array of the lines in
self, 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 given, passes those substrings to the block.
Matching
scan-
Returns an array of substrings matching a given regexp or string, or, if a block given, passes each matching substring to the block.
unpack-
Returns an array of substrings extracted from
selfaccording to a given format.
unpack1-
Returns the first substring extracted from
selfaccording 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 in
self.
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 copy of
self, enclosed in double-quotes, with special characters escaped.
Methods for Iterating
each_byte-
Calls the given block with each successive byte in
self.
each_char-
Calls the given block with each successive character in
self.
each_codepoint-
Calls the given block with each successive integer codepoint in
self.
each_grapheme_cluster-
Calls the given block with each successive grapheme cluster in
self.
each_line-
Calls the given block with each successive line in
self, as determined by a given record separator.
Class methods 2
Instance methods 144
Ruby version changes 3
-
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]
-