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

Discussion in 'Ruby' started by Roger Pack, Feb 16, 2010.

1. ### Roger PackGuest

Is this expected?

>> [1,2,3][0..55]

=> [1, 2, 3]
>> [1,2,3][-5..-1]

=> nil

why not
>> [1,2,3][-5..-1]

=> [1,2,3]

?
Thanks.
-rp
--
Posted via http://www.ruby-forum.com/.

Roger Pack, Feb 16, 2010

2. ### botpGuest

On Tue, Feb 16, 2010 at 8:56 AM, Roger Pack <> wrote:
> why not
>>> [1,2,3][-5..-1]

> => [1,2,3]

but on my case, i'd like both cases to return nil or fail.

best regards -botp

botp, Feb 16, 2010

3. ### Colin BartlettGuest

On Tue, Feb 16, 2010 at 12:56 AM, Roger Pack <> wrote:
> Is this expected?
>
>>> [1,2,3][0..55]

> => [1, 2, 3]
>>> [1,2,3][-5..-1]

> => nil
>
> why not
>>> [1,2,3][-5..-1]

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

Colin Bartlett, Feb 16, 2010