Returns the substring of +self+ specified by the arguments.
Form self[index]
With non-negative integer argument +index+ given,
returns the 1-character substring found in self at character offset index:
'hello'[0] # => "h"
'hello'[4] # => "o"
'hello'[5] # => nil
'Привет'[2] # => "и"
'こんにちは'[4] # => "は"
With negative integer argument +index+ given,
counts backward from the end of +self+:
'hello'[-1] # => "o"
'hello'[-5] # => "h"
'hello'[-6] # => nil
Form self[start, length]
With integer arguments +start+ and +length+ given,
returns a substring of size +length+ characters (as available)
beginning at character offset specified by +start+.
If argument +start+ is non-negative,
the offset is +start+:
'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 +start+ is negative,
counts backward from the end of +self+:
'hello'[-1, 1] # => "o"
'hello'[-5, 5] # => "hello"
'hello'[-1, 0] # => ""
'hello'[-6, 5] # => nil
Special case: if +start+ equals the length of +self+,
returns a new empty string:
'hello'[5, 3] # => ""
Form self[range]
With Range argument +range+ given,
forms substring self[range.start, range.size]:
'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}[rdoc-ref:Regexp@Global+Variables]:
'hello'[/ell/] # => "ell"
'hello'[/l+/] # => "ll"
'hello'[//] # => ""
'hello'[/nosuch/] # => nil
With +capture+ as a positive integer +n+,
returns the +n+th matched group:
'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:
'hello'['ell'] # => "ell"
'hello'[''] # => ""
'hello'['nosuch'] # => nil
'Привет'['ив'] # => "ив"
'こんにちは'['んにち'] # => "んにち"
Related: see {Converting to New String}[rdoc-ref:String@Converting+to+New+String].