Actions
Feature #17279
openAllow a negative step in Range#step with a block
Description
Range#step
prohibits a negative step when a block is given.
>> (6..3).step(-1) {|i| p i }
Traceback (most recent call last):
5: from /home/mrkn/.rbenv/versions/2.7/bin/irb:23:in `<main>'
4: from /home/mrkn/.rbenv/versions/2.7/bin/irb:23:in `load'
3: from /home/mrkn/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/irb-1.2.4/exe/irb:11:in `<top (required)>'
2: from (irb):1
1: from (irb):1:in `step'
ArgumentError (step can't be negative)
But Range#step
allows a negative step when it is called without a block. In this case, Range#step
creates an ArithmeticSequence, and ArithmeticSequence#each
can iterate with a negative step.
>> (6..3).step(-1).each {|i| p i }
6
5
4
3
=> ((6..3).step(-1))
I think the prohibition of a negative step in Range#step
has already been meaningless, so it may be better to permit it for consistency.
Updated by hsbt (Hiroshi SHIBATA) 8 months ago
- Status changed from Open to Assigned
Updated by zverok (Victor Shepelev) 4 months ago
FWIW, my PR with adjusting Range#step
behavior fixes this, too: https://github.com/ruby/ruby/pull/7444 (as part of the unificatioin/simplification process):
From the PR description:
Consistent support for negative step:
p (1..-10).step(-3).to_a
#=> [1, -2, -5, -8] -- ArithmeticSequence backward iteration, on Ruby 3.3 and my code
(1..-10).step(-3) { p _1 }
# Ruby 3.3: step can't be negative (ArgumentError) -- inconsistent with ArithmeticSequence behavior
# my code: prints 1, -2, -5, -8, consistent with ArithmeticSequence
Actions
Like0
Like0Like0