Flowdock
slice(*args) public

Element Reference—If passed a single Fixnum, returns a substring of one character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and with a length given by the second. If passed a range, its beginning and end are interpreted as offsets delimiting the substring to be returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string or the length is negative.

If a Regexp is supplied, the matching portion of str is returned. If a numeric or name parameter follows the regular expression, that component of the MatchData is returned instead. If a String is given, that string is returned if it occurs in str. In both cases, nil is returned if there is no match.

a = "hello there"
a[1]                   #=> "e"
a[2, 3]                #=> "llo"
a[2..3]                #=> "ll"
a[-3, 2]               #=> "er"
a[7..-2]               #=> "her"
a[-4..-2]              #=> "her"
a[-2..-4]              #=> ""
a[12..-1]              #=> nil
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil
Show source
Register or log in to add new notes.