Why does this piece of array return an empty array instead of nil?

Possible duplicate:
Array lattice in Ruby: looking for explanations for illogical behavior (taken from Rubykoans.com)

I played with an array in ruby, but I don't understand the last two results below:

a = [1,2,3] a[2,1] # output is [3] a[3,1] # output is [] ...why?? a[4,1] # output is nil ...according to the docs this makes sense 

Why is a[3,1] an empty array and a[4,1] is nil?

If anything, I expect a[3,1] to return zero as well. According to ruby docs , splitting an array should return nil if the start index is out of range. So why does a[3,1] not return nil?

Note: this is on ruby ​​1.9.2

+4
source share
3 answers

You request the end of the array, which is [] . Look at it this way: Array [1,2,3] can be considered built from cons cells as such: (1, (2, (3, ())) or 1:2:3:[] . Then 3- th index (4th element) clearly [] .

+4
source

"Returns zero if the index (or start index) is out of range."

a[3,1] is a special case according to the example in the same link.

here you can find more information: Slicing an array in Ruby: finding explanations for illogical behavior (taken from Rubykoans.com)

+1
source

It’s easier to understand why, if you present a slice on the left side of the assignment.

 >> (b = a.clone)[2,1] = :a; pb [1, 2, :a] >> (b = a.clone)[2,0] = :b; pb [1, 2, :b, 3] >> (b = a.clone)[3,1] = :c; pb [1, 2, 3, :c] >> (b = a.clone)[3,0] = :d; pb [1, 2, 3, :d] 
0
source

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


All Articles