Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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?

thx

3 Answers

Samuel Webb
Samuel Webb
25,369 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.

arr.push(4)
# 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,168 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