Project

General

Profile

Actions

Feature #18596

closed

Enhance the syntax for getting values in existing arrays.

Added by jackmaple (maple jack) about 2 years ago. Updated about 2 years ago.

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

Description

Hello everyone.
Is it possible to enhance the value syntax in arrays, currently we can pass one or two parameters in the array to take values.

[1,2,3,4,5,6,7,8,9][2]    #result=3
[1,2,3,4,5,6,7,8,9][2,8]  #result=[3, 4, 5, 6, 7, 8, 9]
[1,2,3,4,5,6,7,8,9][-1]   #result=9

Although negative values are supported (from back to front), they are not supported as the second parameter.
The following example is wrong and will not get the desired result.
Is it possible to make the second parameter also support negative values?

[1,2,3,4,5,6,7,8,9][2,-1] #result=nil,the expected result is from index 2 to the end

Sometimes we want to get interval values with step size.

[1,2,3,4,5,6,7,8,9][(2..8).step(2)] #result=[3, 5, 7, 9]

Is it possible to add a third parameter to the array value syntax in order to simplify the syntax?
for example:

[1,2,3,4,5,6,7,8,9][2,8,2] #result=[3, 5, 7, 9]

thanks.

Updated by Eregon (Benoit Daloze) about 2 years ago

  • Status changed from Open to Rejected

[1,2,3,4,5,6,7,8,9][2,-1] #result=nil,the expected result is from index 2 to the end

Use [1,2,3,4,5,6,7,8,9][2..-1].

Is it possible to add a third parameter to the array value syntax in order to simplify the syntax?

Please no, Array#[] is already too complex and this is unnecessary and very unclear.
You can use [1,2,3,4,5,6,7,8,9][(2..8) % 2] which already works and is clearer.

Updated by sawa (Tsuyoshi Sawada) about 2 years ago

jackmaple (maple jack) wrote:

Is it possible to make the second parameter also support negative values?

[1,2,3,4,5,6,7,8,9][2,-1] #result=nil,the expected result is from index 2 to the end

This idea is a duplicate of #15950, which was judged to be weak in motivation (https://bugs.ruby-lang.org/issues/15950#note-11). I agree with you with this idea. Perhaps you can add some use case to persuade Matz.

Updated by Eregon (Benoit Daloze) about 2 years ago

sawa (Tsuyoshi Sawada) wrote in #note-2:

This idea is a duplicate of #15950

Actually not, the suggested semantic is equivalent to array[2..size-1] in this issue, not array[-2..-1] or so.
Which makes it all the clearer a negative number there is just confusing.

Anyway, this was already rejected by matz in #15950 and it seems the OP didn't know the Range is the idiomatic and existing way for this.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0