[LRUG] Array.slice question

Sam Livingston-Gray geeksam at gmail.com
Wed Sep 7 09:37:42 PDT 2011


Someone asked me about this at the last pdxruby beginner's meetup.
(I'd never encountered it, because I hardly ever use array slicing.)
Then, he thoughtfully dug up this StackOverflow question containing
answers, and emailed it to me in a followup message.  (=

http://stackoverflow.com/questions/3568222/array-slicing-in-ruby-looking-for-explanation-for-illogical-behaviour-taken-fro

Hope this helps,
-Sam


> Message: 2
> Date: Wed, 7 Sep 2011 09:29:06 +0100
> From: Michael Pavling <pavling at gmail.com>
> To: London Ruby Users Group <chat at lists.lrug.org>
> Subject: [LRUG] Array.slice question
>
> I'm just running through the Ruby Koans for a bit of fun, and I've
> quickly come upon a case that doesn't make sense to me. I've re-read
> the documentation, but I still don't understand why it happens.
>
> Having a play with this array in the console:
>  >> x = %w(a b c)
>  => ["a", "b", "c"]
>  >> x[1]
>  => "b"
>  >> x[2]
>  => "c"
>  >> x[3]
>  => nil
>
> All makes sense so far, but when I call x[3,0] I *expect* it to return
> nil (as the starting index is out of range), but it returns an empty
> array:
>  >> x[3,0]
>  => []
>
> x[4,0] behaves as I expected:
>  >> x[4,0]
>  => nil
>
> I know it's going to be me not understanding the documentation
> properly, but *unless* I can understand it, it's going to leave me
> confused. Can anyone explain it simply and clearly, please?
>
> TIA



More information about the Chat mailing list