Today I found interesting way to slice array in Ruby:
a = [0,1,2,3,4]
p a[...4] == a[0...4] # True
p a[...4] # [0,1,2,3]
Please explain how this works. (...4) => (nil...4)
. But there is an error when write (...4).to_a
: Cannot Iterate from NilClass.
CodePudding user response:
Ruby 2.6 introduced endless ranges:
# It's the same
2..
2..nil
Range.new(2, nil)
Ruby 2.7 introduced beginless ranges:
# It's the same
..2
nil..2
Range.new(nil, 2)
Array#[]
with range returns a subarray specified by range of indices
Indices start with 0, therefore when use beginless range, it returns subarray from first element to specified one. Similarly for endless
At the same time you doesn't iterate through these ranges, you just take elements that match to the ranges
a = [0, 1, 2, 3, 4]
a[..2] # => [0, 1, 2]
a[2..] # => [2, 3, 4]
But when you try to convert beginless / endless range to array (or try to iterate through it), of course you get exception, because it's impossible to have array with infinite number of elements, array always have size
That's why (2..).to_a
and (..2).to_a
raise exception