Array Methods Flashcards
Ruby Array Methods (Ruby 2.0)
Array[arg]
Returns a new array populated with the given objects. Array.[]( 1, ‘a’, /^A/ ) # => [1, “a”, /^A/] Array[1, ‘a’, /^A/] # => [1, “a”, /^A/] [1, ‘a’, /^A/] # => [1, “a”, /^A/]
ary & ary
Set Intersection — Returns a new array containing elements common to the two arrays, excluding any duplicates. The order is preserved from the original array. [1, 1, 3, 5] & [1, 2, 3] #=> [1, 3] [‘a’, ‘b’, ‘b’, ‘z’] & [‘a’, ‘b’, ‘c’] #=> [‘a’, ‘b’] See also #uniq.
ary * int / ary * string
Repetition — With a String argument, equivalent to ary.join(str). Otherwise, returns a new array built by concatenating the int copies of self. [1, 2, 3] * 3 #=> [1, 2, 3, 1, 2, 3, 1, 2, 3] [1, 2, 3] * “,” #=> “1,2,3”
ary + other_ary
Concatenation — Returns a new array built by concatenating the two arrays together to produce a third array. [1, 2, 3] + [4, 5] #=> [1, 2, 3, 4, 5] a = [“a”, “b”, “c”] a + [“d”, “e”, “f”] a #=> [“a”, “b”, “c”, “d”, “e”, “f”] See also #concat.
ary - other_ary
Array Difference Returns a new array that is a copy of the original array, removing any items that also appear in other_ary. The order is preserved from the original array. It compares elements using their hash and eql? methods for efficiency. [1, 1, 2, 2, 3, 3, 4, 5] - [1, 2, 4] #=> [3, 3, 5] If you need set-like behavior, see the library class Set.
ary << obj
Append—Pushes the given object on to the end of this array. This expression returns the array itself, so several appends may be chained together. [1, 2] << “c” << “d” << [3, 4] #=> [1, 2, “c”, “d”, [ 3, 4] ]
ary other_ary
Comparison — Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other_ary. nil is returned if the two values are incomparable. Each object in each array is compared (using the operator). Arrays are compared in an “element-wise” manner; the first two elements that are not equal will determine the return value for the whole comparison. If all the values are equal, then the return is based on a comparison of the array lengths. Thus, two arrays are “equal” according to Array# if, and only if, they have the same length and the value of each element is equal to the value of the corresponding element in the other array. [“a”, “a”, “c”] [“a”, “b”, “c”] #=> -1 [1, 2, 3, 4, 5, 6] [1, 2] #=> +1
ary == other_ary
Equality — Two arrays are equal if they contain the same number of elements and if each element is equal to (according to Object#==) the corresponding element in other_ary. [“a”, “c”] == [“a”, “c”, 7] #=> false [“a”, “c”, 7] == [“a”, “c”, 7] #=> true [“a”, “c”, 7] == [“a”, “d”, “f”] #=> false
ary[index] ary[start, length] ary[range]
Element Reference — Returns the element at index, or returns a subarray starting at the start index and continuing for length elements, or returns a subarray specified by range of indices. Negative indices count backward from the end of the array (-1 is the last element). For start and range cases the starting index is just before an element. Additionally, an empty array is returned when the starting index for an element range is at the end of the array. Returns nil if the index (or starting index) are out of range.
ary[index] = obj ary[start, length] = obj or other_ary or nil ary[range] = obj or other_ary or nil
Element Assignment — Sets the element at index, or replaces a subarray from the start index for length elements, or replaces a subarray specified by the range of indices. If indices are greater than the current capacity of the array, the array grows automatically. Elements are inserted into the array at start if length is zero. Negative indices will count backward from the end of the array. For start and range cases the starting index is just before an element. An IndexError is raised if a negative index points past the beginning of the array. See also #push, and #unshift.
assoc(obj)
Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==. Returns the first contained array that matches (that is, the first associated array), or nil if no match is found. See also #rassoc
at(index)
Returns the element at index. A negative index counts from the end of self. Returns nil if the index is out of range. See also Array#[]. a = [“a”, “b”, “c”, “d”, “e”] a.at(0) #=> “a” a.at(-1) #=> “e”
bsearch {|x| block }
By using binary search, finds a value from this array which meets the given condition in O(log n) where n is the size of the array. You can use this method in two use cases: a find-minimum mode and a find-any mode. In either case, the elements of the array must be monotone (or sorted) with respect to the block. In find-minimum mode (this is a good choice for typical use case), the block must return true or false, and there must be an index i (0 = 4 } #=> 4 ary.bsearch {|x| x >= 6 } #=> 7 ary.bsearch {|x| x >= -1 } #=> 0 ary.bsearch {|x| x >= 100 } #=> nil In find-any mode (this behaves like libc’s bsearch(3)), the block must return a number, and there must be two indices i and j (0 < i, the block returns zero for ary if i < j, and the block returns a negative number for ary if j < ary.size. Under this condition, this method returns any element whose index is within i…j. If i is equal to j (i.e., there is no element that satisfies the block), this method returns nil.
clear
Removes all elements from self. a = [“a”, “b”, “c”, “d”, “e”] a.clear #=> []
collect { |item| block }
Invokes the given block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect. If no block is given, an Enumerator is returned instead. a = [“a”, “b”, “c”, “d”] a.map { |x| x + “!” } #=> [“a!”, “b!”, “c!”, “d!”] a #=> [“a”, “b”, “c”, “d”]
collect! {|item| block }
Invokes the given block once for each element of self, replacing the element with the value returned by the block. See also Enumerable#collect. If no block is given, an Enumerator is returned instead. a = [“a”, “b”, “c”, “d”] a.map! {|x| x + “!” } a #=> [“a!”, “b!”, “c!”, “d!”]
combination(n) { |c| block }
When invoked with a block, yields all combinations of length n of elements from the array and then returns the array itself. The implementation makes no guarantees about the order in which the combinations are yielded. If no block is given, an Enumerator is returned instead. Examples: a = [1, 2, 3, 4] a.combination(1).to_a #=> [[1],[2],[3],[4]] a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]] a.combination(4).to_a #=> [[1,2,3,4]] a.combination(0).to_a #=> [[]] # one combination of length 0 a.combination(5).to_a #=> [] # no combinations of length 5
compact
Returns a copy of self with all nil elements removed. [“a”, nil, “b”, nil, “c”, nil].compact #=> [“a”, “b”, “c”]
compact!
Removes nil elements from the array. Returns nil if no changes were made, otherwise returns the array. [“a”, nil, “b”, nil, “c”].compact! #=> [“a”, “b”, “c”] [“a”, “b”, “c”].compact! #=> nil
concat(other_ary)
Appends the elements of other_ary to self. [“a”, “b”].concat( [“c”, “d”] ) #=> [“a”, “b”, “c”, “d”] a = [1, 2, 3] a.concat( [4, 5] ) a #=> [1, 2, 3, 4, 5] See also Array#+.
count count(obj) count { |item| block }
Returns the number of elements. If an argument is given, counts the number of elements which equal obj using ===. If a block is given, counts the number of elements for which the block returns a true value. ary = [1, 2, 4, 2] ary.count #=> 4 ary.count(2) #=> 2 ary.count { |x| x%2 == 0 } #=> 3
cycle(n=nil) { |obj| block }
Calls the given block for each element n times or forever if nil is given. Does nothing if a non-positive number is given or the array is empty. Returns nil if the loop has finished without getting interrupted. If no block is given, an Enumerator is returned instead. a = [“a”, “b”, “c”] a.cycle { |x| puts x } # print, a, b, c, a, b, c,.. forever. a.cycle(2) { |x| puts x } # print, a, b, c, a, b, c.
delete(obj) { block }
Deletes all items from self that are equal to obj. Returns the last deleted item, or nil if no matching item is found. If the optional code block is given, the result of the block is returned if the item is not found. (To remove nil elements and get an informative return value, use #compact!) a = [“a”, “b”, “b”, “b”, “c”] a.delete(“b”) #=> “b” a #=> [“a”, “c”] a.delete(“z”) #=> nil a.delete(“z”) { “not found” } #=> “not found”
delete_at(index)
Deletes the element at the specified index, returning that element, or nil if the index is out of range. See also #slice! a = [“ant”, “bat”, “cat”, “dog”] a.delete_at(2) #=> “cat” a #=> [“ant”, “bat”, “dog”] a.delete_at(99) #=> nil
delete_if { |item| block }
Deletes every element of self for which block evaluates to true. The array is changed instantly every time the block is called, not after the iteration is over. See also #reject! If no block is given, an Enumerator is returned instead. scores = [97, 42, 75] scores.delete_if {|score| score < 80 } #=> [97]
drop(n)
Drops first n elements from ary and returns the rest of the elements in an array. If a negative number is given, raises an ArgumentError. See also #take a = [1, 2, 3, 4, 5, 0] a.drop(3) #=> [4, 5, 0]
drop_while { |arr| block }
Drops elements up to, but not including, the first element for which the block returns nil or false and returns an array containing the remaining elements. If no block is given, an Enumerator is returned instead. See also #take_while a = [1, 2, 3, 4, 5, 0] a.drop_while {|i| i < 3 } #=> [3, 4, 5, 0]
each { |item| block }
Calls the given block once for each element in self, passing that element as a parameter. An Enumerator is returned if no block is given. a = [“a”, “b”, “c”] a.each {|x| print x, “ – “ } produces: a – b – c –
each_index { |index| block }
Same as #each, but passes the index of the element instead of the element itself. An Enumerator is returned if no block is given. a = [“a”, “b”, “c”] a.each_index {|x| print x, “ – “ } produces: 0 – 1 – 2 –
empty?
Returns true if self contains no elements. [].empty? #=> true
eql?(other)
Returns true if self and other are the same object, or are both arrays with the same content (according to Object#eql?).
fetch(index) { |index| block }
Tries to return the element at position index, but throws an IndexError exception if the referenced index lies outside of the array bounds. This error can be prevented by supplying a second argument, which will act as a default value. Alternatively, if a block is given it will only be executed when an invalid index is referenced. Negative values of index count from the end of the array. a = [11, 22, 33, 44] a.fetch(1) #=> 22 a.fetch(-1) #=> 44 a.fetch(4, ‘cat’) #=> “cat” a.fetch(100) { |i| puts “#{i} is out of bounds” } #=> “100 is out of bounds”
fill(obj) fill(obj, start [, length]) fill(obj, range ) fill { |index| block } fill(start [, length] ) { |index| block } fill(range) { |index| block }
The first three forms set the selected elements of self (which may be the entire array) to obj. A start of nil is equivalent to zero. A length of nil is equivalent to the length of the array. The last three forms fill the array with the value of the given block, which is passed the absolute index of each element to be filled. Negative values of start count from the end of the array, where -1 is the last element. a = [“a”, “b”, “c”, “d”] a.fill(“x”) #=> [“x”, “x”, “x”, “x”] a.fill(“z”, 2, 2) #=> [“x”, “x”, “z”, “z”] a.fill(“y”, 0..1) #=> [“y”, “y”, “z”, “z”] a.fill { |i| i*i } #=> [0, 1, 4, 9] a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]
find_index(obj) find_index { |item| block } find_index
Returns the index of the first object in ary such that the object is == to obj. If a block is given instead of an argument, returns the index of the first object for which the block returns true. Returns nil if no match is found. See also #rindex. An Enumerator is returned if neither a block nor argument is given. a = [“a”, “b”, “c”] a.index(“b”) #=> 1 a.index(“z”) #=> nil a.index { |x| x == “b” } #=> 1
first first(n)
Returns the first element, or the first n elements, of the array. If the array is empty, the first form returns nil, and the second form returns an empty array. See also #last for the opposite effect. a = [“q”, “r”, “s”, “t”] a.first #=> “q” a.first(2) #=> [“q”, “r”]
flatten!(level)
Flattens self in place. Returns nil if no modifications were made (i.e., the array contains no subarrays.) The optional level argument determines the level of recursion to flatten. a = [1, 2, [3, [4, 5] ] ] a.flatten! #=> [1, 2, 3, 4, 5] a.flatten! #=> nil a #=> [1, 2, 3, 4, 5] a = [1, 2, [3, [4, 5] ] ] a.flatten!(1) #=> [1, 2, 3, [4, 5]]
frozen?
Return true if this array is frozen (or temporarily frozen while being sorted). See also Object#frozen?
hash
Compute a hash-code for this array. Two arrays with the same content will have the same hash code (and will compare using eql?).
include?(object)
Returns true if the given object is present in self (that is, if any element == object), otherwise returns false. a = [“a”, “b”, “c”] a.include?(“b”) #=> true a.include?(“z”) #=> false
index(obj) index { |item| block } index
Returns the index of the first object in ary such that the object is == to obj. If a block is given instead of an argument, returns the index of the first object for which the block returns true. Returns nil if no match is found. See also #rindex. An Enumerator is returned if neither a block nor argument is given. a = [“a”, “b”, “c”] a.index(“b”) #=> 1 a.index(“z”) #=> nil a.index { |x| x == “b” } #=> 1
initialize_copy(other_ary)
Replaces the contents of self with the contents of other_ary, truncating or expanding if necessary. a = [“a”, “b”, “c”, “d”, “e”] a.replace([“x”, “y”, “z”]) #=> [“x”, “y”, “z”] a #=> [“x”, “y”, “z”]
insert(index, obj…)
Inserts the given values before the element with the given index. Negative indices count backwards from the end of the array, where -1 is the last element. a = %w{ a b c d } a.insert(2, 99) #=> [“a”, “b”, 99, “c”, “d”] a.insert(-2, 1, 2, 3) #=> [“a”, “b”, 99, “c”, 1, 2, 3, “d”]
inspect
Creates a string representation of self. [“a”, “b”, “c”].to_s #=> “["a", "b", "c"]” Also aliased as: to_s
join(separator=$,)
Returns a string created by converting each element of the array to a string, separated by the given separator. If the separator is nil, it uses current $,. If both the separator and $, are nil, it uses empty string. [“a”, “b”, “c”].join #=> “abc” [“a”, “b”, “c”].join(“-“) #=> “a-b-c”
keep_if { |item| block }
Deletes every element of self for which the given block evaluates to false. See also #select! If no block is given, an Enumerator is returned instead. a = %w{ a b c d e f } a.keep_if { |v| v =~ /[aeiou]/ } #=> [“a”, “e”]
last last(n)
Returns the last element(s) of self. If the array is empty, the first form returns nil. See also #first for the opposite effect. a = [“w”, “x”, “y”, “z”] a.last #=> “z” a.last(2) #=> [“y”, “z”]
length
Returns the number of elements in self. May be zero. [1, 2, 3, 4, 5].length #=> 5 [].length #=> 0 Also aliased as: size
map { |item| block } map
Invokes the given block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect. If no block is given, an Enumerator is returned instead. a = [“a”, “b”, “c”, “d”] a.map { |x| x + “!” } #=> [“a!”, “b!”, “c!”, “d!”] a #=> [“a”, “b”, “c”, “d”]
map! {|item| block } map!
Invokes the given block once for each element of self, replacing the element with the value returned by the block. See also Enumerable#collect. If no block is given, an Enumerator is returned instead. a = [“a”, “b”, “c”, “d”] a.map! {|x| x + “!” } a #=> [“a!”, “b!”, “c!”, “d!”]
pack ( aTemplateString )
Packs the contents of arr into a binary sequence according to the directives in aTemplateString (see the table below) Directives “A,” “a,” and “Z” may be followed by a count, which gives the width of the resulting field. The remaining directives also may take a count, indicating the number of array elements to convert. If the count is an asterisk (“*”), all remaining array elements will be converted. Any of the directives “sSiIlL” may be followed by an underscore (“_”) or exclamation mark (“!”) to use the underlying platform’s native size for the specified type; otherwise, they use a platform-independent size. Spaces are ignored in the template string. See also String#unpack. a = [“a”, “b”, “c”] n = [65, 66, 67] a.pack(“A3A3A3”) #=> “a b c “ a.pack(“a3a3a3”) #=> “a\000\000b\000\000c\000\000” n.pack(“ccc”) #=> “ABC”
permutation { |p| block } permutation permutation(n) { |p| block } permutation(n)
When invoked with a block, yield all permutations of length n of the elements of the array, then return the array itself. If n is not specified, yield all permutations of all elements. The implementation makes no guarantees about the order in which the permutations are yielded. If no block is given, an Enumerator is returned instead. Examples: a = [1, 2, 3] a.permutation.to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] a.permutation(1).to_a #=> [[1],[2],[3]] a.permutation(2).to_a #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]] a.permutation(3).to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] a.permutation(0).to_a #=> [[]] # one permutation of length 0 a.permutation(4).to_a #=> [] # no permutations of length 4
pop pop(n)
Removes the last element from self and returns it, or nil if the array is empty. If a number n is given, returns an array of the last n elements (or less) just like array.slice!(-n, n) does. See also #push for the opposite effect. a = [“a”, “b”, “c”, “d”] a.pop #=> “d” a.pop(2) #=> [“b”, “c”] a #=> [“a”]
product(other_ary, …) product(other_ary, …) { |p| block }
Returns an array of all combinations of elements from all arrays. The length of the returned array is the product of the length of self and the argument arrays. If given a block, product will yield all combinations and return self instead. [1,2,3].product([4,5]) #=> [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]] [1,2].product([1,2]) #=> [[1,1],[1,2],[2,1],[2,2]] [1,2].product([3,4],[5,6]) #=> [[1,3,5],[1,3,6],[1,4,5],[1,4,6], # [2,3,5],[2,3,6],[2,4,5],[2,4,6]] [1,2].product() #=> [[1],[2]] [1,2].product([]) #=> []
push(obj, … )
Append — Pushes the given object(s) on to the end of this array. This expression returns the array itself, so several appends may be chained together. See also #pop for the opposite effect. a = [“a”, “b”, “c”] a.push(“d”, “e”, “f”) #=> [“a”, “b”, “c”, “d”, “e”, “f”] [1, 2, 3,].push(4).push(5) #=> [1, 2, 3, 4, 5]
rassoc(obj)
Searches through the array whose elements are also arrays. Compares obj with the second element of each contained array using obj.==. Returns the first contained array that matches obj. See also #assoc. a = [[ 1, “one”], [2, “two”], [3, “three”], [“ii”, “two”] ] a.rassoc(“two”) #=> [2, “two”] a.rassoc(“four”) #=> nil
reject {|item| block } reject
Returns a new array containing the items in self for which the given block is not true. See also #delete_if If no block is given, an Enumerator is returned instead.
reject! { |item| block } reject!
Equivalent to #delete_if, deleting elements from self for which the block evaluates to true, but returns nil if no changes were made. The array is changed instantly every time the block is called, not after the iteration is over. See also Enumerable#reject and #delete_if. If no block is given, an Enumerator is returned instead.
repeated_combination(n) { |c| block } repeated_combination(n)
When invoked with a block, yields all repeated combinations of length n of elements from the array and then returns the array itself. The implementation makes no guarantees about the order in which the repeated combinations are yielded. If no block is given, an Enumerator is returned instead. Examples: a = [1, 2, 3] a.repeated_combination(1).to_a #=> [[1], [2], [3]] a.repeated_combination(2).to_a #=> [[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]] a.repeated_combination(3).to_a #=> [[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3], # [1,3,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]] a.repeated_combination(4).to_a #=> [[1,1,1,1],[1,1,1,2],[1,1,1,3],[1,1,2,2],[1,1,2,3], # [1,1,3,3],[1,2,2,2],[1,2,2,3],[1,2,3,3],[1,3,3,3], # [2,2,2,2],[2,2,2,3],[2,2,3,3],[2,3,3,3],[3,3,3,3]] a.repeated_combination(0).to_a #=> [[]] # one combination of length 0
repeated_permutation(n) { |p| block } repeated_permutation(n)
When invoked with a block, yield all repeated permutations of length n of the elements of the array, then return the array itself. The implementation makes no guarantees about the order in which the repeated permutations are yielded. If no block is given, an Enumerator is returned instead. Examples: a = [1, 2] a.repeated_permutation(1).to_a #=> [[1], [2]] a.repeated_permutation(2).to_a #=> [[1,1],[1,2],[2,1],[2,2]] a.repeated_permutation(3).to_a #=> [[1,1,1],[1,1,2],[1,2,1],[1,2,2], # [2,1,1],[2,1,2],[2,2,1],[2,2,2]] a.repeated_permutation(0).to_a #=> [[]] # one permutation of length 0
replace(other_ary)
Replaces the contents of self with the contents of other_ary, truncating or expanding if necessary. a = [“a”, “b”, “c”, “d”, “e”] a.replace([“x”, “y”, “z”]) #=> [“x”, “y”, “z”] a #=> [“x”, “y”, “z”]
reverse
Returns a new array containing self‘s elements in reverse order. [“a”, “b”, “c”].reverse #=> [“c”, “b”, “a”] [1].reverse #=> [1]
reverse!
Reverses self in place. a = [“a”, “b”, “c”] a.reverse! #=> [“c”, “b”, “a”] a #=> [“c”, “b”, “a”]
reverse_each reverse_each
Same as #each, but traverses self in reverse order. a = [“a”, “b”, “c”] a.reverse_each {|x| print x, “ “ } produces: c b a
rindex(obj) rindex { |item| block } rindex
Returns the index of the last object in self == to obj. If a block is given instead of an argument, returns the index of the first object for which the block returns true, starting from the last object. Returns nil if no match is found. See also #index. If neither block nor argument is given, an Enumerator is returned instead. a = [“a”, “b”, “b”, “b”, “c”] a.rindex(“b”) #=> 3 a.rindex(“z”) #=> nil a.rindex { |x| x == “b” } #=> 3
rotate(count=1)
Returns a new array by rotating self so that the element at count is the first element of the new array. If count is negative then it rotates in the opposite direction, starting from the end of self where -1 is the last element. a = [“a”, “b”, “c”, “d”] a.rotate #=> [“b”, “c”, “d”, “a”] a #=> [“a”, “b”, “c”, “d”] a.rotate(2) #=> [“c”, “d”, “a”, “b”] a.rotate(-3) #=> [“b”, “c”, “d”, “a”]
rotate!(count=1)
Rotates self in place so that the element at count comes first, and returns self. If count is negative then it rotates in the opposite direction, starting from the end of the array where -1 is the last element. a = [“a”, “b”, “c”, “d”] a.rotate! #=> [“b”, “c”, “d”, “a”] a #=> [“b”, “c”, “d”, “a”] a.rotate!(2) #=> [“d”, “a”, “b”, “c”] a.rotate!(-3) #=> [“a”, “b”, “c”, “d”]
sample sample(random: rng) sample(n) sample(n, random: rng)
Choose a random element or n random elements from the array. The elements are chosen by using random and unique indices into the array in order to ensure that an element doesn’t repeat itself unless the array already contained duplicate elements. If the array is empty the first form returns nil and the second form returns an empty array. The optional rng argument will be used as the random number generator. a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a.sample #=> 7 a.sample(4) #=> [6, 4, 2, 5]
select { |item| block } select
Returns a new array containing all elements of ary for which the given block returns a true value. If no block is given, an Enumerator is returned instead. [1,2,3,4,5].select { |num| num.even? } #=> [2, 4] a = %w{ a b c d e f } a.select { |v| v =~ /[aeiou]/ } #=> [“a”, “e”] See also Enumerable#select.
select! {|item| block } select!
Invokes the given block passing in successive elements from self, deleting elements for which the block returns a false value. If changes were made, it will return self, otherwise it returns nil. See also #keep_if If no block is given, an Enumerator is returned instead.