[LRUG] Array.slice question
Max Williams
toastkid.williams at gmail.com
Wed Sep 7 03:00:07 PDT 2011
Came out fine for me, and was highly educational! :)
On 7 September 2011 10:22, William Hamilton <whamilton42 at hotmail.com> wrote:
> > > > Having a play with this array in the console:
> > > > >> x = %w(a b c)[...]
> > > 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]
> > > => []
> > The key point is that the 3 in a[3] and the 3 in a[3,0] are not referring
> to the same thing.
> > a[3] is directly accessing an element within the array. a[3,0] is
> accessing a portion of the array. This diagram should help (if the
> formatting makes it through.. copy and paste to fixed-width if it doesn't):
> >
> > 0 1 2 3-------------| a | b | c |------------- 0 1 2
> >
> > Single-integer indexes are at the bottom. They access *elements* of the
> array.Double-integer indexes are at the top. They access *portions* of the
> array.
> > You can see that, technically, starting at the top 3 (which a[3,0] does)
> and counting forwards 0 is still within the array.
> >
> > I think the *reason* Ruby behaves like this for arrays is because it's
> beneficial for Strings (they share the same underlying code, of course). For
> example, it's totally valid to access the end portion of a String, which is
> basically the '' portion just after the final character. If you wanted to
> insert a character at the end of a string, you could do s[3,0] = 'd'.
> >
> > - Will Hamilton
>
>
>
> My poor diagram!
>
> Try this: http://i.imgur.com/I4x96.png
>
>
> - Will Hamilton
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20110907/b4190205/attachment-0003.html>
More information about the Chat
mailing list