Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this array slice return an empty array instead of nil? [duplicate]

Possible Duplicate:
Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)

I've been playing around with array slicing in ruby but I don't understand the last 2 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 would a[3,1] be an empty array while a[4,1] is nil?

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

Note: This is on ruby 1.9.2

like image 409
Dty Avatar asked Apr 07 '11 16:04

Dty


1 Answers

You're asking for the end of the array, which is []. Look at it this way: the Array [1,2,3] can be considered to be constructed from cons cells as such: (1, (2, (3, ())), or 1:2:3:[]. The 3rd index (4th item) is then clearly [].

like image 142
Rein Henrichs Avatar answered Oct 05 '22 11:10

Rein Henrichs