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 Removing Items From Arrays

Javier Pacheco
Javier Pacheco
3,418 Points

.slice removes items from Array.

In video he states that the .slice(0,3) method does not remove items from original Array but the teachers notes state otherwise.

Sam Donald
Sam Donald
36,305 Points

Javier Pacheco

Yeah, that's an error in the teachers notes.

They also say the drop() method takes a number and removes that many items from the front of the array. But we can see from the video it takes them from the end of the array.

1 Answer

Krahr Chaudhury
PLUS
Krahr Chaudhury
Courses Plus Student 139 Points

slice() does NOT remove elements from the original array, it returns a copy of the original array with the elements removed accordingly.

slice!() on the other hand directly modifies the original array.

array1 = [1,2,3,4,5]
array2 = [1,2,3,4,5]

def normal_slice(arr)
  arr.slice(0,3)
  arr
end

def dangerous_slice(arr)
  arr.slice!(0,3)
  arr
end

array1 = normal_slice(array1) #[1,2,3,4,5]
array2 = dangerous_slice(array2) #[4,5]
Sam Donald
Sam Donald
36,305 Points

You're right Koha Choji

When I watched the movie I didn't think his array returned with the sliced items. As for the Teachers notes, I think perhaps they are ill-worded. Since the .slice() method isn't removing anything from the array, perhaps it's best to describe it as collecting and returning items from an array.

Also they describe the .drop() method as "items to remove from the front of the array". This can also be misleading at first, as the returned array will be the items from the original array less the dropped number. Suggesting these are the dropped items. And nothing is actually removed from the original array.

e.g.

array1 = [1,2,3,4,5]
array2 = array1.drop(2) 

array2 # => [3,4,5] 
# Ok cool so these items have been dropped and removed from array1 ?

array1 # => [1,2,3,4,5] 
# Ohh, nothing was removed from array1 and the returned array  from .dop()
# is everything after item 2 (index 1)