From: sawadatsuyoshi@... Date: 2019-06-22T12:12:20+00:00 Subject: [ruby-core:93316] [Ruby trunk Feature#15950] Allow negative length in `Array#[]`, `Array#[]=`, `String#[]`, `String#[]=` Issue #15950 has been updated by sawa (Tsuyoshi Sawada). shevegen (Robert A. Heiler) wrote: > > "abcdefgh"[0, -3] # => "fgh" > > I guess my brain got confused here, since the 0 would put my brain to > assume to "start at the most left position". So that code confused me. It is the same idea as negative index. If you did not have the concept of cyclng, then you would be surprised with negative index too. You would need to say "0 lets me assume to start at the left most position. If I had a negative index instead, then what can be even more left of thar?" The key to this is cycling: to assume that the left end is attached to the right end so that you can continuously move beyond this border. I suggested to apply that notion to index. To give a metaphor, there is a video game called Pac Man, in which if you keep moving the character leftward past the left edge of the screen, you appear from the right egde, still moving leftward. I have not mentioned that, for consistency, my proposal would also expect another change in the output of code to be like this: ```ruby "abcdefgh"[-1, 3] # => "abc" ``` And needless to say, this proposal would be irrelevant to Ruby beginners who insist on needlessly creating a range object as in `"abcdefg"[0...3]` to take the first three characters of the string, when you can, and should, do `"abcdefg"[0, 3]`, which is more straightforward and efficient. ---------------------------------------- Feature #15950: Allow negative length in `Array#[]`, `Array#[]=`, `String#[]`, `String#[]=` https://bugs.ruby-lang.org/issues/15950#change-78790 * Author: sawa (Tsuyoshi Sawada) * Status: Rejected * Priority: Normal * Assignee: * Target version: ---------------------------------------- To take the first n characters of a string, using `[]` is straightforward: ```ruby "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: ```ruby "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). ```ruby "abcdefgh"[0, -3] # => "fgh" "abcdefgh"[5, -3] # => "cde" ``` If there is not enough characters or elements, it should stop at the boundary. ```ruby "abcdefgh"[1, -3] # => "a" ``` -- https://bugs.ruby-lang.org/ Unsubscribe: