Array [array.size ..- 1] does not return nil

I noticed strange behavior when Rangeused as an index Array. (At least this is strange to me.)

a = [1,2,3]
=> [1, 2, 3]
a[3]
=> nil
a[3..-1]
=> []
a[4]
=> nil
a[4..-1]
=> nil

I thought that a[3..-1]returns nil, but for some reason returns []. a[-3..-4]also returns [].

Can someone explain why it returns []when I use range limit values?

+4
source share
1 answer

Because when range.begin == array.length, he always returns []. This is noted as a “special case” in the Ruby documentation :

a = [ "a", "b", "c", "d", "e" ]
# special cases
a[5]                   #=> nil
a[6, 1]                #=> nil
a[5, 1]                #=> []
a[5..10]               #=> []
+4
source

Source: https://habr.com/ru/post/1568332/


All Articles