1

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.

enter image description here

My version of ruby is => ruby 1.9.3p327 (2012-11-10 revision 37606) [x86_64-darwin12.2.0]

1
  • 1
    Instead of speculating, perhaps reading the documentation for Array would have answered your questions. Commented Apr 17, 2013 at 2:28

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.