From: daniel@...42.com Date: 2020-06-26T19:08:11+00:00 Subject: [ruby-core:98963] [Ruby master Feature#16812] Allow slicing arrays with ArithmeticSequence Issue #16812 has been updated by Dan0042 (Daniel DeLorme). mrkn (Kenta Murata) wrote in #note-7: > It may be better to change the behavior of `[*0..10][-100..100]` I somewhat agree with that. When using range slicing most combinations make sense: ```ruby [*0..10][0..4] #first elements [*0..10][-5..-1] #last elements [*0..10][1..-2] #middle elements ``` But a negative start with a non-negative end is quite weird. What is that operation even supposed to mean? What is it useful for? ```ruby [*0..10][-8..8] #???? 8.times{ |i| p (0..i) => [*0..i][-3..3] } {0..0=>nil} {0..1=>nil} {0..2=>[0, 1, 2]} {0..3=>[1, 2, 3]} {0..4=>[2, 3]} {0..5=>[3]} {0..6=>[]} {0..7=>[]} ``` So even if `[*0..10][-100..100]` remains supported forever (there doesn't seem to be a point in breaking compatibility; see #16822), it could emit a verbose-mode warning. And ArithmeticSequence slicing should not attempt to be consistent with that case, because it's useless to start with. So I believe there are two useful/meaningful possibilities for `(0..20).to_a[(-5..5) % 2]` a) `[16, 18, 20]` ignore trailing non-negative values, like `(-5..) % 2`; I think this makes the most sense b) `[1, 3, 5]` ignore leading negative values, like python ---------------------------------------- Feature #16812: Allow slicing arrays with ArithmeticSequence https://bugs.ruby-lang.org/issues/16812#change-86339 * Author: zverok (Victor Shepelev) * Status: Assigned * Priority: Normal * Assignee: matz (Yukihiro Matsumoto) ---------------------------------------- I believe when concepts of ArithmeticSequence and `Range#%` were introduced, one of the main intended usages was array slicing in scientific data processing. So, it seems to make sense to allow this in `Array#[]`: ```ruby ary[(5..20) % 2] # each second element between 5 and 20 ary[(0..) % 3] # each third element ary[10.step(by: -1)] # elements 10, 9, 8, 7 .... ``` PR is [here](https://github.com/ruby/ruby/pull/3055). My reasoning is as follows: 1. As stated above, ArithmeticSequence and `Range#%` seem to have been introduced exactly for this goal 2. Python has its slicing syntax as `begin:end:step` (with a possibility to omit either), and it seems to be well respected and used feature for data processing. So I believe it is useful, and relatively easy to integrate into existing functionality I expect the usual "it is ugly and unreadable!" backlash. I don't have an incentive, nor energy, to "defend" the proposal, so I would not. -- https://bugs.ruby-lang.org/ Unsubscribe: