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