3

I got this question when doing ruby koans. Given this array:

array = [1, 2, 3, 4]

array[4, 0] equals []. However, array[5, 0] equals nil.

Both 4 and 5 are out of index. Why do they return different things?

Kingston Chan
  • 923
  • 2
  • 8
  • 25

1 Answers1

7

The first parameter of Array#slice(start,length) is the place between indices where slicing should begin :

array = [1, 2, 3, 4]
# elements            : [   1   2   3   4   ]
#                         ↑   ↑   ↑   ↑   ↑
# slice start indices :   0   1   2   3   4

slice(0,_) begins left of 1, slice(3,_) begins left of 4, and slice(4,_) begins at the last possible place : right of 4.

slice(4,0) is still inside array, it's the empty Array right of 4.

slice(5,0) isn't inside array anymore, it's nil.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
  • 2
    This design decision totally violates the principal of least astonishment – Jeremiah Rose Jun 15 '22 at 07:04
  • @JeremiahRose: It's true that it might be surprising at first. Also : "in a May 2005 discussion on the newsgroup comp.lang.ruby, Matsumoto attempted to distance Ruby from POLA, explaining that because any design choice will be surprising to someone, he uses a personal standard in evaluating surprise. " from https://en.wikipedia.org/wiki/Ruby_(programming_language). – Eric Duminil Jun 15 '22 at 07:47