Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Collections Ruby Arrays Adding Items to Arrays

Sven Vanlandschoot
Sven Vanlandschoot
11,252 Points

3 different ways to add items to the end of a list?

I see that there are 3 ways to add items to the end of a list. Can someone explain or give some examples when you should use the different methodes?


3 Answers

Samuel Webb
Samuel Webb
25,370 Points

The only reason I can think would be that it depends on what you want as a return value. For instance, you have this array:

arr = [1,2,3]

If you use the :push method, the entire array would be the return value.

# returns [1, 2, 3, 4]

But if you did it in the following way, not sure what it's called, you would only get the number you're adding as a return value.

arr[3] = 4
# returns 4

# or

arr[arr.length] = 4
# also returns 4

Since functions, loops and conditional will automatically return the last evaluated value, any of these could be useful depending on the situation. If you want to add something to an array and then tell the person just what they added, the second options are better. But if you want to show someone the whole array after they add something, the :push method is better. Depending on what you want as a return value, you'll end up saving a line or 2 on code by choosing the right one.

Matthew Salt
Matthew Salt
3,876 Points

Not sure if this will help anyone, but it's not really explained that well in the video.

<< accepts a single argument and adds it to the end of the array .push can take multiple arguments and adds to the end of the array in the order it was typed. += Produces a new array. As a consequence, repeated use of += on arrays can be quite inefficient.

Sven Vanlandschoot
Sven Vanlandschoot
11,252 Points

Ah oki so the only thing that is different is the output for the user. Thx alot for the info