unable to go "left" of an array, but yes "right" of an array

C

Colin Bartlett

Is this expected?
[1,2,3][0..55] => [1, 2, 3]
[1,2,3][-5..-1]
=> nil

why not
=> [1,2,3]

My understanding is that what decides whether a slice or nil is returned
is whether the _starting_ point of the potential slice is "in" the array.
So that is what I'd expect, albeit I think one could reasonably have
different conventions, such as the ones you and botp suggest.

What does seem maybe a bit strange to me are the "??" below:,

a = [0, 1, 2] #=> [0, 1, 2]
a[0, 5] #=> [0, 1, 2]
a[0.75, 5] #=> [0, 1, 2]
a[1, 5] #=> [1, 2]
a[2, 5] #=> [2]
a[3, 5] #=> [] ?? (1)
a[3.75, 5] #=> [] ?? (1)
a[4, 5] #=> nil
a[4.75, 5] #=> nil
a[-1, 5] #=> [2]
a[-2, 5] #=> [1, 2]
a[-3, 5] #=> [0, 1, 2]
a[-4, 5] #=> nil
a[-0.75, 5] #=> [0, 1, 2] ?? (2)
a[-1.75, 5] #=> [2] ?? (2)
a[-2.75, 5] #=> [1, 2] ?? (2)
a[-3.75, 5] #=> [0, 1, 2] ?? (2)
a[-4.75, 5] #=> nil

(1) Are there many people who want this usage, instead of wanting nil?

(2) These seem to use f.truncate === f.to_int === Integer( f ),
instead of f.floor for the start of the slice.
Assuming allowing floats as indexes of arrays is reasonable
(and I'm agnostic on the point for now), I'm very unsure
whether I'd prefer using to_int or floor to convert
a non-integer index to an integer.
I can see arguments for and against either option.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top