Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

ruby - Why does array.slice behave differently for (length, n)

If I have an array a:

  1. a[a.length] returns nil. Good.
  2. a[a.length, x] returns []. Good.
  3. a[a.length+x, y] returns nil. Inconsistent with 2.

While this behavior is documented, it seems odd.

Can anybody explain the reasons behind this design?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Consider this

a = [0, 1, 2, 3] #=> [0, 1, 2, 3]
a[0, 10]         #=> [0, 1, 2, 3]
a[1, 10]         #=>    [1, 2, 3]
a[2, 10]         #=>       [2, 3]
a[3, 10]         #=>          [3]
a[4, 10]         #=>           []
a[5, 10]         #=>          nil

So a[4, 10] is the slice between the 3 and the end of the array which is []

Where as a[4] and a[5, 10] are accessing elements that aren't in the array

It may help to think of the slice points as being between the elements, rather than the elements themselves.

[ <0> 0 <1> 1 <2> 2 <3> 3 <4> ]

Where <n> are the points between elements and the start/end of the array. a[4, 10] then becomes a selection of 10 elements, starting from point 4. Whereas a[5, 10] starts from point 5, which is not part of the list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...