Commit 14e6d11
Ciaran McCrisken
(IAC-1414) Throw error in range() function when step size invalid
Prior to this commit, on Ruby 2.7, the range() method would NOT
throw an ArgumentError exception if it was passed an invalid value as the
step size (3rd arg). Instead, it would return an array of size
1,000,000 with repeated integer values of the 2nd arg.
The function invokes Ruby's in built range method and `step` to
define a step size to increment / decrement by and then passes the
output to `first`, limiting to the first 1,000,000 values.
On Ruby < 2.7, `step` would throw an `ArgumentError` if the step
size passed was `0`:
```
1..2).step(0).first(1_000_000).to_a
Traceback (most recent call last):
5: from ~/.rvm/rubies/ruby-2.5.8/bin/irb:11:in `<main>'
4: from (irb):7
3: from (irb):7:in `first'
2: from (irb):7:in `each'
1: from (irb):7:in `step'
ArgumentError (step can't be 0)
```
However, on Ruby 2.7, the `step` method returns an Enumerator that
will then subsequently generate an Array of the size specified when
passed to `first`, made up of the 2nd arg value (last):
```
(1..2).step(0).first(10).to_a
=> [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
```
This is an issue, as the 3rd arg is passed to `to_i`, which then
becomes the step size. For any values that cannot be converted to
a positive / negative (or legit 0) Integer, a 0 is returned.
This commit will perform a check on the value of `step` and throw
an ArgumentError if it is not zero.1 parent 9a8f097 commit 14e6d11
1 file changed
+2
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
51 | 51 | | |
52 | 52 | | |
53 | 53 | | |
| 54 | + | |
| 55 | + | |
54 | 56 | | |
55 | 57 | | |
56 | 58 | | |
| |||
0 commit comments