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

Common Array Methods

There’s way more that you can do with arrays besides creating them and printing their values. The Array class defines and inherits a couple dozen methods that serve various purposes (Table 4.1). Some more array methods, in particular each and map, will be discussed in Chapter 5. Both are used to walk through an array one element at a time.

Table 4.1. Array Methods




True if the array is empty


The first value in the array


True if the array includes the given value


The index number of a given value


The array in a printable format


The last value in the array


The number of items in the array


The array in reverse order


The array sorted


The unique values in the array

The methods listed in Table 4.1 are easy to understand and use (as the next sequence of steps will show), so I’ll devote extra time to some others. To return a subset of an array, use slice. Its first argument is the indexed position of the item to be returned. Its second (and optional) argument is the number of items to return from that point forward:

n = ["a", "b", "c", "d", "e"]
n.slice(0) # "a"
n.slice(2, 2) # ["c", "d"]

Note that this method will return the matching subset without affecting the original array. If you want to permanently remove the elements, still returning them in the process, use slice!.

The slice method does the same thing as using the square brackets after the array’s name. Placing a single digit within square brackets returns a single element:

n[0] # "a"

Using [x,y] returns y elements starting at position x:

n[2, 2] # ["c", "d"]

Or you can use first and last to return the first or last x number of elements:

n.last # "e"
n.last(2) # ["d, e"]
n.first(3) # ["a", "b", "c"]

Finally, in the process of demonstrating the use of some of these methods, I’ll frequently invoke inspect. This method, which can be used with many types of objects, returns the variable to which it’s applied in a more accessible format. With arrays, this means the contents will be displayed on one line, instead of over several.

To use array methods:

  1. Create two arrays:

    numbers = [0.4, 23.0, 23.3, 0.4, 5.2]
    dwarfs = ['Doc', 'Sleepy',
    → 'Bashful', 'Grumpy', 'Happy',
    → 'Sneezy', 'Dopey']

    The first array is a list of floats, two of which have the same value. The second array is the seven dwarfs that stumbled upon Snow White.

  2. Check for specific values in each array:

    puts numbers.include?(23.0)
    puts dwarfs.include?('Donner')

    The include? method returns a Boolean value indicating if a given value is present in an array.

  3. Find the location of specific values in each array (Figure 4.4):

    puts dwarfs.index('Grumpy')
    puts numbers.index(0.4)
    puts numbers.rindex(0.4)
    puts dwarfs.index('Papa Smurf')
    Figure 4.4

    Figure 4.4 Thanks to Ruby and include?, I can easily see that Donner wasn’t one of the Seven Dwarfs! Other examples use the index method, which returns the location of a given value in an array.

    The index method returns the integer location of a value, if found in the array. Note that it returns the location of the first found value, so in the numbers array, calling index points to the first element. Conversely, rindex finds the last found value. If the value isn’t in the array, as is the case with Papa Smurf, nil is returned.

  4. Re-order and display the arrays (Figure 4.5):

    puts numbers.sort.inspect
    puts dwarfs.sort.reverse.inspect
    Figure 4.5

    Figure 4.5 The two arrays, redisplayed in different order.

    The sort method will arrange a list of numbers in increasing order and arrange strings in alphabetical order. The reverse method is applied to the sorted dwarfs array to turn it into a reverse-alphabetical order list. In both cases, inspect is called so that the array is printed more succinctly (rather than over multiple lines, as would ordinarily be the case).

  5. Cut some values from an array (Figure 4.6):

    puts dwarfs.length
    oops = dwarfs.slice!(2, 2)
    puts dwarfs.length
    Figure 4.6

    Figure 4.6 The length method returns the number of elements in an array, and the slice! method cuts a subsection out of an array (poor Bashful, poor Grumpy).

    To see the full effect of slice!, the length method is first called to show the number of items in the array. Then the oops array is created (after an accident in the mine), assigning to it two of the dwarfs. Finally, the length method is called again to confirm that the dwarfs array is now down two elements.

    Note that the oops array now contains the values of those two elements (indexed at 0 and 1) and that the last two elements in the dwarfs array have been reindexed (in other words, there’s no gap in the integer locations). Finally, if slice had been used instead of slice!, oops would still contain the same two names but the dwarfs array would retain all seven values.

  6. Return only the unique values in an array (Figure 4.7):

    puts numbers.uniq.inspect
    puts numbers.length
    puts numbers.uniq.length
    Figure 4.7

    Figure 4.7 To find only the unique values in an array, apply the uniq method.

    The uniq method returns an array of unique values (without impacting the original array). With the numbers variable, which has two 0.4 values in it, the returned unique array contains one less element. To confirm this, the length method is called on both versions of the array.

  • + Share This
  • 🔖 Save To Your Account