[LRUG] Array.slice question
William Hamilton
whamilton42 at hotmail.com
Wed Sep 7 02:22:22 PDT 2011
> > > 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20110907/af3829aa/attachment-0003.html>
More information about the Chat
mailing list