Project

General

Profile

Actions

Feature #15950

closed

Allow negative length in `Array#[]`, `Array#[]=`, `Array#slice`, `Array#slice!`, `String#[]`, `String#[]=`, `String#slice`, `String#slice!`

Added by sawa (Tsuyoshi Sawada) almost 5 years ago. Updated over 4 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:93308]

Description

To take the first n characters of a string, using [] is straightforward:

"abcdefgh"[0, 3] # => "abc"

But to take the last n characters, we need to use n in two arguments: in the index (in negative form) in addition to the length:

"abcdefgh"[-3, 3] # => "fgh"

This is cumbersome.

I wish negative length to be allowed, and be interpreted as measuring leftward (while cycling the receiver if necessary).

"abcdefgh"[0, -3] # => "fgh"
"abcdefgh"[5, -3] # => "cde"

If there is not enough characters or elements, it should stop at the boundary.

"abcdefgh"[1, -3] # => "a"
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0