class 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:

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:

Each of these methods takes:

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:

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:

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:

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:

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]

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:

Here, class String provides methods that are useful for:

Methods for Creating a String

Methods for a Frozen/Unfrozen String

Methods for Querying

Counts

Substrings

Encodings

Other

Methods for Comparing

Methods for Modifying a String

Each of these methods modifies self.

Insertion

Substitution

Casing

Encoding

Deletion

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

Encoding

Substitution

Casing

Deletion

Duplication

Methods for Converting to Non-String

Each of these methods converts the contents of self to a non-String.

Characters, Bytes, and Clusters

Splitting

Matching

Numerics

Strings and Symbols

Methods for Iterating