Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#[]

string[index] → new_string or nil
string[start, length] → new_string or nil
string[range] → new_string or nil
string[regexp, capture = 0] → new_string or nil
string[substring] → new_string or nil

Returns the substring of self specified by the arguments.

When the single Integer argument index is given, returns the 1-character substring found in self at offset index:

Example
'bar'[2] # => "r"

Counts backward from the end of self if index is negative:

Example
'foo'[-3] # => "f"

Returns nil if index is out of range:

Example
'foo'[3] # => nil
'foo'[-4] # => nil

When the two Integer arguments start and length are given, returns the substring of the given length found in self at offset start:

Example
'foo'[0, 2] # => "fo"
'foo'[0, 0] # => ""

Counts backward from the end of self if start is negative:

Example
'foo'[-2, 2] # => "oo"

Special case: returns a new empty String if start is equal to the length of self:

Example
'foo'[3, 2] # => ""

Returns nil if start is out of range:

Example
'foo'[4, 2] # => nil
'foo'[-4, 2] # => nil

Returns the trailing substring of self if length is large:

Example
'foo'[1, 50] # => "oo"

Returns nil if length is negative:

Example
'foo'[0, -1] # => nil

When the single Range argument range is given, derives start and length values from the given range, and returns values as above:

  • 'foo'[0..1] is equivalent to 'foo'[0, 2].

  • 'foo'[0...1] is equivalent to 'foo'[0, 1].

When the Regexp argument regexp is given, and the capture argument is 0, returns the first matching substring found in self, or nil if none found:

Example
'foo'[/o/] # => "o"
'foo'[/x/] # => nil
s = 'hello there'
s[/[aeiou](.)\1/] # => "ell"
s[/[aeiou](.)\1/, 0] # => "ell"

If argument capture is given and not 0, it should be either an Integer capture group index or a String or Symbol capture group name; the method call returns only the specified capture (see Regexp Capturing):

Example
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, nil is returned. If an invalid capture group name is given, IndexError is raised.

When the single String argument substring is given, returns the substring from self if found, otherwise nil:

Example
'foo'['oo'] # => "oo"
'foo'['xx'] # => nil

String#slice is an alias for String#[].

Ruby version changes

  1. 3.0
See also #[]= #=~ #=== #ascii_only? also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0