Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

String#slice

(::int start, ?::int length) -> ::String?
(::range[::int?] range) -> ::String?
(::Regexp regexp, ?::MatchData::capture backref) -> ::String?
(::String substring) -> ::String?
slice(*args)

Alias of #[]

Returns the substring of self specified by the arguments.

Form self[offset]

With non-negative integer argument offset given, returns the 1-character substring found in self at character offset offset:

Example
'hello'[0]    # => "h"
'hello'[4]    # => "o"
'hello'[5]    # => nil
'こんにちは'[4] # => "は"

With negative integer argument offset given, counts backward from the end of self:

Example
'hello'[-1] # => "o"
'hello'[-5] # => "h"
'hello'[-6] # => nil

Form self[offset, size]

With integer arguments offset and size given, returns a substring of size size characters (as available) beginning at character offset specified by offset.

If argument offset is non-negative, the offset is offset:

Example
'hello'[0, 1]  # => "h"
'hello'[0, 5]  # => "hello"
'hello'[0, 6]  # => "hello"
'hello'[2, 3]  # => "llo"
'hello'[2, 0]  # => ""
'hello'[2, -1] # => nil

If argument offset is negative, counts backward from the end of self:

Example
'hello'[-1, 1] # => "o"
'hello'[-5, 5] # => "hello"
'hello'[-1, 0] # => ""
'hello'[-6, 5] # => nil

Special case: if offset equals the size of self, returns a new empty string:

Example
'hello'[5, 3]  # => ""

Form self[range]

With Range argument range given, forms substring self[range.start, range.size]:

Example
'hello'[0..2]  # => "hel"
'hello'[0, 3]  # => "hel"

'hello'[0...2] # => "he"
'hello'[0, 2]  # => "he"

'hello'[0, 0]  # => ""
'hello'[0...0] # => ""

Form self[regexp, capture = 0]

With Regexp argument regexp given and capture as zero, searches for a matching substring in self; updates Regexp-related global variables:

Example
'hello'[/ell/]     # => "ell"
'hello'[/l+/]      # => "ll"
'hello'[//]        # => ""
'hello'[/nosuch/]  # => nil

With capture as a positive integer n, returns the nth matched group:

Example
'hello'[/(h)(e)(l+)(o)/]    # => "hello"
'hello'[/(h)(e)(l+)(o)/, 1] # => "h"
$1                          # => "h"
'hello'[/(h)(e)(l+)(o)/, 2] # => "e"
$2                          # => "e"
'hello'[/(h)(e)(l+)(o)/, 3] # => "ll"
'hello'[/(h)(e)(l+)(o)/, 4] # => "o"
'hello'[/(h)(e)(l+)(o)/, 5] # => nil

Form self[substring]

With string argument substring given, returns the matching substring of self, if found:

Example
'hello'['ell']      # => "ell"
'hello'['']         # => ""
'hello'['nosuch']   # => nil
'こんにちは'['んにち'] # => "んにち"

Related: see Converting to New String.

Ruby version changes

  1. 3.0
See also #[] #slice! #size #shellsplit also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0