6

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

Community
  • 1
  • 1
Dty
  • 12,253
  • 6
  • 43
  • 61

3 Answers3

5

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 [].

Rein Henrichs
  • 15,437
  • 1
  • 45
  • 55
2

" Returns nil if the index (or starting index) are out of range."

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

more info can be seen here by the way: Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)

Community
  • 1
  • 1
corroded
  • 21,406
  • 19
  • 83
  • 132
0

It's easier to understand why if you imagine the slice on the left side of an assignment.

>> (b = a.clone)[2,1] = :a; p b
[1, 2, :a]
>> (b = a.clone)[2,0] = :b; p b
[1, 2, :b, 3]
>> (b = a.clone)[3,1] = :c; p b
[1, 2, 3, :c]
>> (b = a.clone)[3,0] = :d; p b
[1, 2, 3, :d]
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • Is this just an alternate way to push to the array? – Dty Apr 07 '11 at 16:52
  • do you know of a situation when something like this would be useful? Right now I'm more curious about the WHY than the HOW. – Dty Apr 19 '11 at 05:09