Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
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:
'bar'[2] # => "r"
Counts backward from the end of self if index is negative:
'foo'[-3] # => "f"
Returns nil if index is out of range:
'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:
'foo'[0, 2] # => "fo"
'foo'[0, 0] # => ""
Counts backward from the end of self if start is negative:
'foo'[-2, 2] # => "oo"
Special case: returns a new empty String if start is equal to the length of self:
'foo'[3, 2] # => ""
Returns nil if start is out of range:
'foo'[4, 2] # => nil
'foo'[-4, 2] # => nil
Returns the trailing substring of self if length is large:
'foo'[1, 50] # => "oo"
Returns nil if length is negative:
'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:
'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):
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:
'foo'['oo'] # => "oo"
'foo'['xx'] # => nil
String#slice is an alias for String#[].
               static VALUE
rb_str_aref_m(int argc, VALUE *argv, VALUE str)
    if (argc == 2) {
        if (RB_TYPE_P(argv[0], T_REGEXP)) {
            return rb_str_subpat(str, argv[0], argv[1]);
        else {
            long beg = NUM2LONG(argv[0]);
            long len = NUM2LONG(argv[1]);
            return rb_str_substr(str, beg, len);
    rb_check_arity(argc, 1, 2);
    return rb_str_aref(str, argv[0]);

Was this page useful?