webdevjeff.us

Web Developer Jeff George

Work

Ruby Array Methods

A reference sheet of useful methods for Ruby arrays.

Nov. 1, 2015

Array Methods Index

Iteration

About this
reference sheet

Information

Retrieval

Manipulation

Reordering

Iteration Methods

These methods iterate over the array, executing a code block on each item, generally returning either a new array or nil. #map! is the only destructive method included in this section.

Array#each { |item| block }

Action: Executes block on each item in array.

Returns: The original array, unchanged.

  • [1,2,3].each { |i| puts i.to_s + "?" }
  • 1?
  • 2?
  • 3?
  • => [1, 2, 3]

Array#each_index { |index| block }

Action: Executes block on each item.

Returns: The original array, unchanged.

  • ary = ['|','*','+','^']
  • ['|','*','+'].each_index { |i| puts array[i] * i }

  • *
  • ++
  • ^^^
  • => ["|", "*", "+", "^"]

Enum#each_slice(int) { |slice| block }

Action: Executes block on each slice of int length.

Returns: nil.

  • [1,2,3,4,5,6].each_slice(2) { |slice| p slice }
  • [1, 2]
  • [3, 4]
  • [5, 6]
  • => nil

Array#reverse_each { |item| block }

Action: Executes block on each on each item, iterating from last to first.

Returns: The original array, unchanged.

  • [1,2,3].reverse_each { |i| puts i.to_s + "^"}
  • 3^
  • 2^
  • 1^
  • => [1, 2, 3]

Array#cycle(integer) { |item| block }

Action: Executes block on each on each item in collection (integer) times.

Returns: nil.

Note: When called without an integer argument, #cycle will continue to loop indefinitely.

  • [1,2,3].cycle(2) { |i| puts i.to_s + '|'}
  • 1|
  • 2|
  • 3|
  • 1|
  • 2|
  • 3|
  • => nil

Array#map { |item| block }

Action: Executes block on each on each item.

Returns: New array of values changed by block.

  • arr = [1,2,3]
  • arr.map { |i| puts i * 2 }
  • 2
  • 4
  • 6
  • => [2, 4, 6]
  • arr
  • => [1, 2, 3]

Array#map! { |item| block }

Action: Executes block on each on each item, changing the array in place.

Returns: The amended array, with values changed by block. Destructive.

  • arr = [1,2,3,4]
  • arr.map! { |i| i * 2 }
  • => [2, 4, 6, 8]
  • arr
  • => [2, 4, 6, 8]

Information Methods

These methods return information about the array or the items it contains, without making any changes to the original array. These methods are non-destructive.

Array#length

Returns: Number of items in array.

Note: #size and #count are synonyms for #length.

  • [1,2,3,4,5,6].length
  • => 6

Array#count

Returns: Number of items in array.

Note: Called without an argument, #count is a synonym for #length. #count(object) returns the number of times object occurs in array. #count { |item| block } returns the number of items in the array that evaluate to true for the block.

  • #count
  • ['a','b','a','c','a','b'].count
  • => 6
  • #count(object)
  • ['a','b','a','c','a','b'].count('b')
  • => 2
  • #count { |item| block }
  • nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  • nums.count{ |i| i % 2 == 0 && i % 3 == 0 }
  • => 2

Array#all? { |item| block }

Returns: true if all items in array evaluate to true for block.

  • [1,2,3,4,5,6].all? { |i| i.is_a?(Fixnum) }
  • => true
  • [1,2,3,'a','b','c'].all? { |i| i.is_a?(Fixnum) }
  • => false

Enumerable#none? { |item| block }

Returns: true if no items in array evaluate to true for block.

  • [1,2,3,4,5,6].all? { |i| i.is_a?(String)
  • => true
  • [1,2,3,'a','b','c'].all? { |i| i.is_a?(String) }
  • => false

Enumerable#any? { |item| block }

Returns: true if one or more items in array evaluate to true for block.

  • [1,2,3,4,5,6].any? { |i| i.is_a?(String)
  • => false
  • [1,2,3,'a','b','c'].all? { |i| i.is_a?(String) }
  • => true

Enumerable#one? { |item| block }

Returns: true if exactly one item in array evaluates to true for block.

  • [1,2,3,4,5,6].one? { |i| i = 20 / 5 }
  • => true
  • [1,2,3,4,5,6].one? { |i| i % 2 == 0 }
  • => false

Array#include?(object)}

Returns: true if object is present in array.

  • [1,2,3,4,5,6].include?(4)
  • => true
  • [1,2,3,4,5,6].include?("4")
  • => false

Array#index(object)}

Returns: Index of first occurence of object in array.

Note: #find_index is a synonym for #index. Called with a block, #index { |item| block } returns index of the first item for which block returns true.

  • #index(object)
  • ['a','b','a','c','a','b'].index('b')
  • => 1
  • #index { |item| block }
  • [2,4,6,8,10,12].index { |i| i % 3 == 0 )
  • => 2

Array#rindex(object)}

Returns: Index of last occurence of object in array.

Note: Called with a block, #rindex { |item| block } returns index of last item for which block evaluates to true.

  • #rindex(object)
  • ['a','b','a','c','a','b'].index('b')
  • => 5
  • #rindex { |item| block }
  • [3,4,5,6,7,8,9,10,11,12].index { |i| i%5 == 0 )
  • => 9

Data Retrieval Methods

These methods return a specified item, or an array of specified items, without making any changes to the original array. These methods are non-destructive.

Array#slice(index)

Returns: Item at index.

Notes: Synonymous with Array#[index]. Called with two arguments, #slice(index, quantity) returns a new array of quantity items from the original array, starting at index. Called with a range argument, #slice(range) returns a new array of items at the range of indices.

  • #slice(index)
  • ['a','b','a','c','a','b'].slice(3)
  • => "c"
  • #slice(index, quantity)
  • ['a','b','a','c','a','b'].slice(2, 3)
  • => ["a", "c", "a"]
  • #slice(range)
  • ['a','b','a','c','a','b'].slice(2..4)
  • => ["a", "c", "a"]

Array#values_at(index,…)

Returns: A new array of items from the specified indices.

Note: When called with a range argument, #values_at is synonymous with #slice(range).

  • ['a','b','c','d','e','f'].values_at(1,4,5)
  • => ["b", "e", "f"]

Array#take(integer)

Returns: A new array of the first integer items.

  • ['a','b','c','d','e','f'].take(3)
  • => ["a", "b", "c"]

Array#take_while ( |item| block)

Returns: A new array containing all items up to the first item that evaluates to false for the block.

  • [1,2,3,4,5,6,7,8].take_while { |x| x < 5 }
  • => [1, 2, 3, 4]

Array#drop(integer)

Returns: A new array, excluding the first integer items.

  • ['a','b','c','d','e','f'].drop(2)
  • => ["c", "d", "e", "f"]

Array#drop_while ( |item| block)

Returns: A new array excluding all items up to the first item that evaluates to false for the block.

  • [1,2,3,4,5,6,7,8].drop_while { |x| x < 7 }
  • => [7, 8]

Array#first

Returns: The first item in the array.

Note: When called with an integer argument, #first(int) returns the first integer items. #first(int) is synonymous with #take(int).

  • #first
  • ['a','b','c','d','e','f'].first
  • => "a"
  • #first(integer)
  • ['a','b','c','d','e','f'].first(3)
  • => ["a", "b", "c"]

Array#last

Returns: The last item in the array.

Note: When called with an integer argument, #last(int) returns the last integer items.

  • #last
  • ['a','b','c','d','e','f'].last
  • => "f"
  • #last(integer)
  • ['a','b','c','d','e','f'].last(2)
  • => ["e", "f"]

Array#find

Returns: The first item for which the block evaluates to true.

Note: #detect is a synonym for #find.

  • ary = [1,2,3,4,5,6,7,8,9,10,11,12]
  • ary.find { |item| item%2 == 0 && item%3 == 0 }
  • => 6

Array#select

Returns: A new array containing every item for which the block evaluates to true.

Note: #find_all is a synonym for #select.

  • ary = [1,2,3,4,5,6,7,8,9,10,11,12]
  • ary.find { |item| item%2 == 0 && item%3 == 0 }
  • => [6, 12]

Array#reject

Returns: A new array containing every item for which the block evaluates to false.

  • ary = [1,2,3,4,5,6,7,8,9,10,11,12]
  • ary.find { |item| item % 5 == 0 }
  • => [1, 2, 3, 4, 6, 7, 8, 9, 11, 12]

Array#sample

Returns: A randomly-chosen item from the array.

Note: When called with an integer argument, #sample(int) returns an array of int randomly-chosen items, without repeating items (unless items appear more than once in the array).

  • #sample
  • [1,2,3,4,5,6,7,8,9,10].sample
  • => 3
  • #sample(integer)
  • [1,2,3,4,5,6,7,8,9,10].sample(4)
  • => [5, 9, 6, 2]

Array#uniq

Returns: A new array with any duplicate values deleted.

  • ["a","b","a","c","a","b"].uniq
  • => ["a", "b", "c"]

Enumerable#max

Returns: The largest item in the array.

Note: When called with an integer argument, #max(int) returns an array of the int largest items.

  • #max
  • [4, 7, 2, 10, 1, 5, 9, 6].max
  • => 10
  • #max(integer)
  • [4, 7, 2, 10, 1, 5, 9, 6].max(3)
  • => [10, 9, 7]

Enumerable#max_by { |item| block }

Returns: The largest item in the array, based on the value returned for each item by the block.

Note: When called with an integer argument, #max_by(int) returns an array of the int largest items.

  • #max_by { |item| block }
  • ary = ["apple", "banana", "canteloupe", "date"]
  • ary.max_by { |word| word.length }
  • => "canteloupe"
  • #max_by(integer) { |item| block }
  • ary.max_by(2) { |word| word.length }
  • => ["canteloupe", "banana"]

Enumerable#min

Returns: The smallest item in the array.

Note: When called with an integer argument, #min(int) returns an array of the int smallest items.

  • #min
  • [4, 7, 2, 10, 1, 5, 9, 6].min
  • => 1
  • #min(integer)
  • [4, 7, 2, 10, 1, 5, 9, 6].min(3)
  • => [1, 2, 4]

Enumerable#min_by { |item| block }

Returns: The smallest item in the array, based on the value returned for each item by the block.

Note: When called with an integer argument, #min_by(int) returns an array of the int smallest items.

  • #min_by { |item| block }
  • ary = ["apple", "banana", "canteloupe", "date"]
  • ary.min_by { |word| word.length }
  • => "date"
  • #min_by(integer) { |item| block }
  • ary.min_by(2) { |word| word.length }
  • => ["date", "apple"]

Enumerable#minmax

Returns: A new array containing the smallest and largest items in the array.

  • [4, 7, 2, 10, 1, 5, 9, 6].minmax
  • => [1, 10]

Enumerable#minmax_by { |item| block }

Returns: A new array containing the smallest and largest item in the array, based on the value returned for each item by the block.

  • ary = ["apple", "banana", "canteloupe", "date"]
  • ary.minmax_by { |word| word.length }
  • => ["date", "canteloupe"]

Enum#reduce(mem) { |mem, item| block }

Action: Reduces the array to a single value by executing block on each item of the array. The mem variable stores the cumulative value. If the initial value of mem is not set in the argument, it will be set to the first item in the array.

Returns: The final value for mem.

  • # With no initial value for mem:
  • [1,2,3,4,5].reduce { |m, i| m + i }
  • => 15
  • # With initial value for mem:
  • [1,2,3,4,5].reduce(10) { |m, i| m + i }
  • => 25

Note: When called with a symbol argument, #reduce(symbol) passes each item in array into symbol's method, which is called on the mem value. An initial value for mem can also be included in the argument, as in #reduce(mem, symbol).

  • # With no initial value for mem:
  • [1,2,3,4,5].reduce(:+)
  • => 15
  • # With initial value for mem:
  • [1,2,3,4,5].reduce(20, :+)
  • => 35

Example: In this snippet, #reduce is used with the ternary operator to find the largest number in the set (which duplicates the functionality of #max).

  • array = [4, 7, 2, 10, 0, 5, 9, 6]
  • array.reduce { |m, i| m > i ? m : i }
  • => 10

Array#join

Returns: A string formed by converting all items in the array into a single string.

Note: If a string argument is added, #join(string) will insert that string between items as a separator.

  • #join
  • ['a', 'b', 'c', 'd', 'e'].join
  • => "abcdef"
  • #join(string)
  • ['a', 'b', 'c', 'd', 'e'].join(" - ")
  • => "a - b - c - d - e"

Enumerable#partition { |item| block }

Returns: An array of two arrays, in which the first array includes all items in the original array that evaluate to true for block, and the second array includes all items that evaluate to false.

  • ary = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • ary.partition { |num| num.even? }
  • => [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]

Object#clone

Returns: A new array with a new object id, with values equal to those in original array.

Note: #clone is a useful first step when writing an original, non-destructive method that must incorporate a naturally-descructive method.

  • [1,2,3,4,5,6].clone
  • => [1,2,3,4,5,6]

Manipulation Methods

These methods add and delete items from an existing array. These methods are destructive, regardless of whether they carry the ! character.

Array#slice!(index)

Action: Deletes the item at from the original array.

Returns: Item at index.

Note: Called with two integer arguments, #slice!(index, quantity) deletes quantity items beginning at index, and returns an array containing the deleted items. Called with a range argument, #slice!(range) deletes items at the indices specified by the range, and returns them.

  • #slice!(index)
  • ary = ['a','b','c','d','e','f','g']
  • ary.slice!(3)
  • => "d"
  • ary
  • => ["a", "b", "c", "e", "f", "g"]
  • #slice!(index, quantity)
  • ary = ['a','b','c','d','e','f','g']
  • ary.slice!(2, 3)
  • => ["c", "d", "e"]
  • ary
  • => ["a", "b", "f", "g"]
  • #slice!(range)
  • ary = ['a','b','c','d','e','f','g']
  • ary.slice!(1..4)
  • => ["b", "c", "d", "e"]
  • ary
  • => ["a", "f", "g"]

Array#push(obj, …)

Action: Appends object(s) to the end of the array.

Returns: The amended array.

  • ary = ['a','b','c']
  • ary.push('x','y','z')
  • => ["a", "b", "c", "x", "y", "z"]
  • ary
  • => ["a", "b", "c", "x", "y", "z"]

Array#pop

Action: Deletes last item from end of array.

Returns: The deleted item.

Note: Called with an integer argument, #pop(integer) deletes the last integer items from the original array, and returns them as a new array.

  • #pop
  • ary = ['a','b','c','d','e']
  • ary.pop
  • => "e"
  • ary
  • => ["a", "b", "c", "d"]
  • #pop(integer)
  • ary = ['a','b','c','d','e']
  • ary.pop(2)
  • => ["d", "e"]
  • ary
  • => ["a", "b", "c"]

Array#unshift(obj,…)

Action: Inserts object(s) at the start of the array.

Returns: The amended array.

  • ary = ['a','b','c']
  • ary.unshift('x','y','z')
  • => ["x", "y", "z", "a", "b", "c"]
  • ary
  • => ["x", "y", "z", "a", "b", "c"]

Array#shift

Action: Deletes item from the start of the array.

Returns: The deleted item.

Note: Called with an integer argument, #shift(integer) deletes the last integer items from the original array, and returns them as a new array.

  • #shift
  • ary = ['a','b','c','d','e']
  • ary.pop
  • => "a"
  • ary
  • => ["b", "c", "d", "e"]
  • #shift(integer)
  • ary = ['a','b','c','d','e']
  • ary.shift(2)
  • => ["a", "b"]
  • ary
  • => ["c", "d", "e"]

Array#insert(index, obj, …)

Action: Inserts object(s) at the specified index of the array.

Returns: The amended array.

  • ary = ['a','b','c']
  • ary.insert(2, 'x','y','z')
  • => ["a", "b", "x", "y", "z", "c"]
  • ary
  • => ["a", "b", "x", "y", "z", "c"]

Array#delete(object)

Action: Deletes all occurences of the object from the array.

Returns: The last object deleted, or nil if no objects were deleted.

Note: Called with a code block, #delete(object) { block } executes block if object is not found within array.

  • #delete(obj)
  • ary = ['a','b','a','c','a','b']
  • ary.delete('b')
  • => "b"
  • ary
  • => ["a", "a", "c", "a"]
  • #delete(obj) { block }
  • ary = ['a','b','a','c','a','b']
  • ary.delete('z') { 'not found' }
  • => "not found"
  • ary
  • => ["a", "b", "a", "c", "a", "b"]

Array#select! { |item| block }

Action: Deletes from the array every item for which block evaluates to false.

Returns: The amended array, or nil if all items evaluated to true for the block.

Note: #keep_if is a synonym for #select!.

  • ary = [1,2,3,4,5,6,7,8,9,10,11,12]
  • ary.select! { |i| i % 3 == 0 }
  • => [3, 6, 9, 12]
  • ary
  • => [3, 6, 9, 12]

Array#reject! { |item| block }

Action: Deletes from the array every item for which block evaluates to true.

Returns: The amended array, or nil if all items evaluated to false for the block.

Note: #delete_if is a synonym for #reject!.

  • ary = [1,2,3,4,5,6,7,8,9,10,11,12]
  • ary.reject! { |i| i % 3 == 0 }
  • => [1, 2, 4, 5, 7, 8, 10, 11]
  • ary
  • => [1, 2, 4, 5, 7, 8, 10, 11]

Array#concat(other_array)

Action: Appends all items in other_array to the end of the original array.

Returns: The amended array.

  • ary = ['a','b','c']
  • ary.concat(['x','y','z'])
  • => ["a", "b", "c", "x", "y", "z"]
  • ary
  • => ["a", "b", "c", "x", "y", "z"]

Array#replace(other_array)

Action: Replaces all items in array with the contents of other_array.

Returns: The amended array.

  • ary = ['a','b','c']
  • ary.replace(['x','y','z'])
  • => ["x", "y", "z"]
  • ary
  • => ["x", "y", "z"]

Array#uniq!

Action: Deletes duplicate items from the array.

Returns: The amended array, or nil if the array included no duplicate items.

  • ary = ['a','b','a','c','a','b']
  • ary.uniq!
  • => ["a", "b", "c"]
  • ary
  • => ["a", "b", "c"]

Array#compact!

Action: Deletes nil items from the array.

Returns: The amended array.

  • ary = ['a','b',nil,'c',nil,'b']
  • ary.uniq!
  • => ["a", "b", "c", "b"]
  • ary
  • => ["a", "b", "c", "b"]

Array#clear

Action: Deletes all items from the array.

Returns: The newly-empty array.

  • ary = ['apple', 'banana', 'canteloupe']
  • ary.clear
  • => []
  • ary
  • => []

Reordering Methods

These methods reorder or rearrange the original array. Most of these methods have destructive versions, indicated with a !, so read the notes carefully.

Array#sort

Action: Sorts the array in alphanumeric order.

Returns: A new, sorted array.

Note: #sort is not destructive. #sort! is the destructive version; #sort! sorts the original array in place and returns it.

  • ['c','e','b','d','f','a'].sort
  • => ["a", "b", "c", "d", "e", "f"]

Array#shuffle

Action: Shuffles the array in random order.

Returns: A new, shuffled array.

Note: #shuffle is not destructive. #shuffle! is the destructive version; #shuffle! shuffles the original array in place and returns it.

  • ['a','b','c','d','e','f'].shuffle
  • => ["c", "d", "a", "e", "f", "b"]

Array#reverse

Action: Reverses the order of the items in the array.

Returns: A new, reversed array.

Note: #reverse is not destructive. #reverse! is the destructive version; #reverse! reverses the original array in place and returns it.

  • ['a','b','c','d','e','f'].reverse
  • => ["f", "e", "d", "c", "b", "a"]

Array#rotate(index)

Action: Rotates the items in the array so that the item at index moves to index 0.

Returns: A new, rotated array.

Note: #rotate is not destructive. #rotate! is the destructive version; #rotate! rotates the original array in place and returns it.

  • ['a','b','c','d','e','f'].rotate(4)
  • => ["e", "f", "a", "b", "c", "d"]

Array#flatten

Action: Called upon nested arrays, returns a new array with all nested arrays flattened to a single array.

Returns: A new, flattened array.

Note: Called with an integer argument, #flatten(int) will flatten the nested arrays by int levels.

Note: #flatten is not destructive. #flatten! is the destructive version; #flatten! flattens the original array in place and returns it.

  • #flatten
  • ary = [1,2, [3,4, [5,6, [7,8,9,10], 11], 12], 13]
  • ary.flatten
  • => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
  • #flatten(integer)
  • ary = [1,2, [3,4, [5,6, [7,8,9,10], 11], 12], 13]
  • ary.flatten(2)
  • => [1, 2, 3, 4, 5, 6, [7, 8, 9, 10], 11, 12, 13]

Array#transpose

Action: Called upon a two-dimensional array (rows and columns), returns a new array with the rows and columns switched.

Returns: A new, transposed two-dimensional array.

Note: #transpose is not destructive. There is no #transpose! version.

  • [[1, 2], [3, 4], [5, 6]].transpose
  • => [[1, 3, 5], [2, 4, 6]]