Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Removing Elements

Just as you can add new elements to existing arrays, you can remove elements, too. To remove the last element from the array, use pop:

a = [1, 2]
a.pop # a = [1]

To remove an item from the beginning of the array, use shift:

a = [1, 2, 3, 4]
a.shift # a = [2, 3, 4]

To remove an item from the middle of the array, use delete_at, providing it the index position of the item to be deleted:

a = [1, 2, 3, 4, 5, 6]
a.delete_at(2) # a = [1, 2, 4, 5, 6]

To remove an item from the array based upon its value, use delete:

pets = ['cat', 'dog', 'rabbit', 'parrot']
# pets = ['cat', 'rabbit', 'parrot']

Each of these methods not only removes the element from the array but also returns the removed value (just like slice!).

To remove elements:

  1. Create a new array:

    groceries = %w{milk kiwis carrots
    → tofu steak beets salt turnips}

    Using the %w technique discussed in the first section of the chapter, I’ll quickly create a list of words (the %w means that each array element is separated by a space, so that quotes are not required).

  2. Remove the second item from the array (Figure 4.11):

    puts groceries.inspect
    Figure 4.11

    Figure 4.11 An array is created and one value removed.

  3. Remove tofu from the list:

    puts groceries.inspect
  4. Remove the first and last items (Figure 4.12).

    puts groceries.inspect
    Figure 4.12

    Figure 4.12 More array elements are removed using three different methods.

  • + Share This
  • 🔖 Save To Your Account