ruby/doc/string/aref.rdoc
2025-10-10 16:39:05 -04:00

99 lines
2.6 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Returns the substring of +self+ specified by the arguments.
<b>Form <tt>self[index]</tt></b>
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
<b>Form <tt>self[start, length]</tt></b>
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] # => ""
<b>Form <tt>self[range]</tt></b>
With Range argument +range+ given,
forms substring <tt>self[range.start, range.size]</tt>:
'hello'[0..2] # => "hel"
'hello'[0, 3] # => "hel"
'hello'[0...2] # => "he"
'hello'[0, 2] # => "he"
'hello'[0, 0] # => ""
'hello'[0...0] # => ""
<b>Form <tt>self[regexp, capture = 0]</tt></b>
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
<b>Form <tt>self[substring]</tt></b>
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].