Reputation: 5821
I have been playing around with the projects on learnstreet but I sort of noticed something intresting about the way that they access elements in an array and was hoping to get some clarification. To access the first element in an array, I know that I can do something like
a = [2,4,5,6,7]
a[0]
output=> 2
However on the learnstreet site they access the first element by doing something like
a = [2,4,5,6,7]
a[0,1]
output => 2
My speculations might be that they are using an older version of ruby that requires that you that. Correct me if I am wrong, am just curious to why it was done that way.
Actually to verify this, I went a step further and tried it in pry but I noticed that using their approach only returned the first element of the array.
My version of ruby is => ruby 1.9.3p327 (2012-11-10 revision 37606) [x86_64-darwin12.2.0]
Upvotes: 1
Views: 479
Reputation: 1060
The best of grabbing the n number of index values
a[0..1]
It will return 0 index to index 1 eg:- a = [2,4,5,6,7]
a[0..1]
output => [2,4]
It will be neat and clean but it will return the value in array not in string.
Upvotes: 2
Reputation: 33360
That is just another way of grabbing the first index saying:
a[0, 1]
Start at the 0 index and grab a slice of length one. This is useful for grabbing a "chunk" or "slice" of the array. Typically, when only involving a certain item of the array, it is clearer to use the single index version. Namely a[0]
.
See here for more clarification.
Upvotes: 6