Array Methods Flashcards

Ruby Array Methods (Ruby 2.0)

1
Q

Array[arg]

A

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/]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

ary & ary

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

ary * int / ary * string

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

ary + other_ary

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

ary - other_ary

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

ary << obj

A

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] ]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

ary other_ary

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

ary == other_ary

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

ary[index] ary[start, length] ary[range]

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

ary[index] = obj ary[start, length] = obj or other_ary or nil ary[range] = obj or other_ary or nil

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

assoc(obj)

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

at(index)

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

bsearch {|x| block }

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

clear

A

Removes all elements from self. a = [“a”, “b”, “c”, “d”, “e”] a.clear #=> []

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

collect { |item| block }

A

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”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

collect! {|item| block }

A

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!”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

combination(n) { |c| block }

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

compact

A

Returns a copy of self with all nil elements removed. [“a”, nil, “b”, nil, “c”, nil].compact #=> [“a”, “b”, “c”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

compact!

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

concat(other_ary)

A

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#+.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

count count(obj) count { |item| block }

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

cycle(n=nil) { |obj| block }

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

delete(obj) { block }

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

delete_at(index)

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
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]
26
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]
27
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]
28
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 --
29
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 --
30
empty?
Returns true if self contains no elements. [].empty? #=\> true
31
eql?(other)
Returns true if self and other are the same object, or are both arrays with the same content (according to Object#eql?).
32
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"
33
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]
34
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
35
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"]
36
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]]
37
frozen?
Return true if this array is frozen (or temporarily frozen while being sorted). See also Object#frozen?
38
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?).
39
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
40
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
41
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"]
42
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"]
43
inspect
Creates a string representation of self. ["a", "b", "c"].to\_s #=\> "[\"a\", \"b\", \"c\"]" Also aliased as: to\_s
44
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"
45
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"]
46
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"]
47
length
Returns the number of elements in self. May be zero. [1, 2, 3, 4, 5].length #=\> 5 [].length #=\> 0 Also aliased as: size
48
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"]
49
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!"]
50
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"
51
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
52
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"]
53
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([]) #=\> []
54
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]
55
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
56
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.
57
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.
58
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
59
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
60
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"]
61
reverse
Returns a new array containing self‘s elements in reverse order. ["a", "b", "c"].reverse #=\> ["c", "b", "a"] [1].reverse #=\> [1]
62
reverse!
Reverses self in place. a = ["a", "b", "c"] a.reverse! #=\> ["c", "b", "a"] a #=\> ["c", "b", "a"]
63
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
64
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
65
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"]
66
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"]
67
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]
68
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.
69
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.
70
shift shift(n)
Removes the first element of self and returns it (shifting all other elements down by one). Returns nil if the array is empty. If a number n is given, returns an array of the first n elements (or less) just like array.slice!(0, n) does. With ary containing only the remainder elements, not including what was shifted to new\_ary. See also #unshift for the opposite effect. args = ["-m", "-q", "filename"] args.shift #=\> "-m" args #=\> ["-q", "filename"] args = ["-m", "-q", "filename"] args.shift(2) #=\> ["-m", "-q"] args #=\> ["filename"]
71
shuffle shuffle(random: rng)
Returns a new array with elements of self shuffled. a = [1, 2, 3] #=\> [1, 2, 3] a.shuffle #=\> [2, 3, 1] The optional rng argument will be used as the random number generator. a.shuffle(random: Random.new(1)) #=\> [1, 3, 2]
72
shuffle! shuffle!(random: rng)
Shuffles elements in self in place. The optional rng argument will be used as the random number generator.
73
slice(index) slice(start, length) slice(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. a = ["a", "b", "c", "d", "e"] a[2] + a[0] + a[1] #=\> "cab" a[6] #=\> nil a[1, 2] #=\> ["b", "c"] a[1..3] #=\> ["b", "c", "d"] a[4..7] #=\> ["e"] a[6..10] #=\> nil a[-3, 3] #=\> ["c", "d", "e"] # special cases a[5] #=\> nil a[6, 1] #=\> nil a[5, 1] #=\> [] a[5..10] #=\> []
74
slice!(index) slice!(start, length) slice!(range)
Deletes the element(s) given by an index (optionally up to length elements) or by a range. Returns the deleted object (or objects), or nil if the index is out of range. a = ["a", "b", "c"] a.slice!(1) #=\> "b" a #=\> ["a", "c"] a.slice!(-1) #=\> "c" a #=\> ["a"] a.slice!(100) #=\> nil a #=\> ["a"]
75
sort sort { |a, b| block }
Returns a new array created by sorting self. Comparisons for the sort will be done using the operator or using an optional code block. The block must implement a comparison between a and b, and return -1, when a follows b, 0 when a and b are equivalent, or +1 if b follows a. See also Enumerable#sort\_by. a = ["d", "a", "e", "c", "b"] a.sort #=\> ["a", "b", "c", "d", "e"] a.sort { |x,y| y x } #=\> ["e", "d", "c", "b", "a"]
76
sort! sort! { |a, b| block }
Sorts self in place. Comparisons for the sort will be done using the operator or using an optional code block. The block must implement a comparison between a and b, and return -1, when a follows b, 0 when a and b are equivalent, or +1 if b follows a. See also Enumerable#sort\_by. a = ["d", "a", "e", "c", "b"] a.sort! #=\> ["a", "b", "c", "d", "e"] a.sort! { |x,y| y x } #=\> ["e", "d", "c", "b", "a"]
77
sort\_by! { |obj| block } sort\_by!
Sorts self in place using a set of keys generated by mapping the values in self through the given block. If no block is given, an Enumerator is returned instead.
78
take(n)
Returns first n elements from the array. If a negative number is given, raises an ArgumentError. See also #drop a = [1, 2, 3, 4, 5, 0] a.take(3) #=\> [1, 2, 3]
79
take\_while { |arr| block } take\_while
Passes elements to the block until the block returns nil or false, then stops iterating and returns an array of all prior elements. If no block is given, an Enumerator is returned instead. See also #drop\_while a = [1, 2, 3, 4, 5, 0] a.take\_while { |i| i \< 3 } #=\> [1, 2]
80
to\_a
Returns self. If called on a subclass of Array, converts the receiver to an Array object.
81
transpose
Assumes that self is an array of arrays and transposes the rows and columns. a = [[1,2], [3,4], [5,6]] a.transpose #=\> [[1, 3, 5], [2, 4, 6]] If the length of the subarrays don’t match, an IndexError is raised.
82
uniq uniq { |item| ... }
Returns a new array by removing duplicate values in self. If a block is given, it will use the return value of the block for comparison. It compares values using their hash and eql? methods for efficiency. a = ["a", "a", "b", "b", "c"] a.uniq # =\> ["a", "b", "c"] b = [["student","sam"], ["student","george"], ["teacher","matz"]] b.uniq { |s| s.first } # =\> [["student", "sam"], ["teacher", "matz"]]
83
uniq! uniq! { |item| ... }
Removes duplicate elements from self. If a block is given, it will use the return value of the block for comparison. It compares values using their hash and eql? methods for efficiency. Returns nil if no changes are made (that is, no duplicates are found). a = ["a", "a", "b", "b", "c"] a.uniq! # =\> ["a", "b", "c"] b = ["a", "b", "c"] b.uniq! # =\> nil c = [["student","sam"], ["student","george"], ["teacher","matz"]] c.uniq! { |s| s.first } # =\> [["student", "sam"], ["teacher", "matz"]]
84
unshift(obj, ...)
Prepends objects to the front of self, moving other elements upwards. See also #shift for the opposite effect. a = ["b", "c", "d"] a.unshift("a") #=\> ["a", "b", "c", "d"] a.unshift(1, 2) #=\> [1, 2, "a", "b", "c", "d"]
85
values\_at(selector, ...)
Returns an array containing the elements in self corresponding to the given selector(s). The selectors may be either integer indices or ranges. See also #select. a = %w{ a b c d e f } a.values\_at(1, 3, 5) # =\> ["b", "d", "f"] a.values\_at(1, 3, 5, 7) # =\> ["b", "d", "f", nil] a.values\_at(-1, -2, -2, -7) # =\> ["f", "e", "e", nil] a.values\_at(4..6, 3...6) # =\> ["e", "f", nil, "d", "e", "f"]
86
zip(arg, ...) zip(arg, ...) { |arr| block }
Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument. This generates a sequence of ary.size n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than the size of the initial array, nil values are supplied. If a block is given, it is invoked for each output array, otherwise an array of arrays is returned. a = [4, 5, 6] b = [7, 8, 9] [1, 2, 3].zip(a, b) #=\> [[1, 4, 7], [2, 5, 8], [3, 6, 9]] [1, 2].zip(a, b) #=\> [[1, 4, 7], [2, 5, 8]] a.zip([1, 2], [8]) #=\> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]
87
ary | other\_ary
Set Union — Returns a new array by joining ary with other\_ary, excluding any duplicates and preserving the order from the original array. It compares elements using their hash and eql? methods for efficiency. ["a", "b", "c"] | ["c", "d", "a"] #=\> ["a", "b", "c", "d"] See also #uniq.
88
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/]
Array[arg]
89
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 & ary
90
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 \* int / ary \* string
91
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
92
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 - other\_ary
93
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 \<\< obj
94
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
95
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 == other\_ary
96
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] ary[start, length] ary[range]
97
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.
ary[index] = obj ary[start, length] = obj or other\_ary or nil ary[range] = obj or other\_ary or nil
98
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
assoc(obj)
99
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"
at(index)
100
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.
bsearch {|x| block }
101
Removes all elements from self. a = ["a", "b", "c", "d", "e"] a.clear #=\> []
clear
102
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 }
103
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!"]
collect! {|item| block }
104
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
combination(n) { |c| block }
105
Returns a copy of self with all nil elements removed. ["a", nil, "b", nil, "c", nil].compact #=\> ["a", "b", "c"]
compact
106
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
compact!
107
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#+.
concat(other\_ary)
108
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
count count(obj) count { |item| block }
109
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.
cycle(n=nil) { |obj| block }
110
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(obj) { block }
111
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\_at(index)
112
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]
delete\_if { |item| block }
113
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(n)
114
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]
drop\_while { |arr| block }
115
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 { |item| block }
116
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 --
each\_index { |index| block }
117
Returns true if self contains no elements. [].empty? #=\> true
empty?
118
Returns true if self and other are the same object, or are both arrays with the same content (according to Object#eql?).
eql?(other)
119
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"
fetch(index) { |index| block }
120
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]
fill(obj) fill(obj, start [, length]) fill(obj, range ) fill { |index| block } fill(start [, length] ) { |index| block } fill(range) { |index| block }
121
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
find\_index(obj) find\_index { |item| block } find\_index
122
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"]
first first(n)
123
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]]
flatten!(level)
124
Return true if this array is frozen (or temporarily frozen while being sorted). See also Object#frozen?
frozen?
125
Compute a hash-code for this array. Two arrays with the same content will have the same hash code (and will compare using eql?).
hash
126
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
include?(object)
127
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
index(obj) index { |item| block } index
128
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"]
initialize\_copy(other\_ary)
129
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"]
insert(index, obj...)
130
Creates a string representation of self. ["a", "b", "c"].to\_s #=\> "[\"a\", \"b\", \"c\"]" Also aliased as: to\_s
inspect
131
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"
join(separator=$,)
132
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"]
keep\_if { |item| block }
133
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"]
last last(n)
134
Returns the number of elements in self. May be zero. [1, 2, 3, 4, 5].length #=\> 5 [].length #=\> 0 Also aliased as: size
length
135
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
136
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!"]
map! {|item| block } map!
137
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"
pack ( aTemplateString )
138
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
permutation { |p| block } permutation permutation(n) { |p| block } permutation(n)
139
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"]
pop pop(n)
140
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([]) #=\> []
product(other\_ary, ...) product(other\_ary, ...) { |p| block }
141
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]
push(obj, ... )
142
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
rassoc(obj)
143
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
144
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.
reject! { |item| block } reject!
145
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\_combination(n) { |c| block } repeated\_combination(n)
146
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
repeated\_permutation(n) { |p| block } repeated\_permutation(n)
147
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"]
replace(other\_ary)
148
Returns a new array containing self‘s elements in reverse order. ["a", "b", "c"].reverse #=\> ["c", "b", "a"] [1].reverse #=\> [1]
reverse
149
Reverses self in place. a = ["a", "b", "c"] a.reverse! #=\> ["c", "b", "a"] a #=\> ["c", "b", "a"]
reverse!
150
Same as #each, but traverses self in reverse order. a = ["a", "b", "c"] a.reverse\_each {|x| print x, " " } produces: c b a
reverse\_each reverse\_each
151
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
rindex(obj) rindex { |item| block } rindex
152
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)
153
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"]
rotate!(count=1)
154
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]
sample sample(random: rng) sample(n) sample(n, random: rng)
155
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
156
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.
select! {|item| block } select!
157
Removes the first element of self and returns it (shifting all other elements down by one). Returns nil if the array is empty. If a number n is given, returns an array of the first n elements (or less) just like array.slice!(0, n) does. With ary containing only the remainder elements, not including what was shifted to new\_ary. See also #unshift for the opposite effect. args = ["-m", "-q", "filename"] args.shift #=\> "-m" args #=\> ["-q", "filename"] args = ["-m", "-q", "filename"] args.shift(2) #=\> ["-m", "-q"] args #=\> ["filename"]
shift shift(n)
158
Returns a new array with elements of self shuffled. a = [1, 2, 3] #=\> [1, 2, 3] a.shuffle #=\> [2, 3, 1] The optional rng argument will be used as the random number generator. a.shuffle(random: Random.new(1)) #=\> [1, 3, 2]
shuffle shuffle(random: rng)
159
Shuffles elements in self in place. The optional rng argument will be used as the random number generator.
shuffle! shuffle!(random: rng)
160
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. a = ["a", "b", "c", "d", "e"] a[2] + a[0] + a[1] #=\> "cab" a[6] #=\> nil a[1, 2] #=\> ["b", "c"] a[1..3] #=\> ["b", "c", "d"] a[4..7] #=\> ["e"] a[6..10] #=\> nil a[-3, 3] #=\> ["c", "d", "e"] # special cases a[5] #=\> nil a[6, 1] #=\> nil a[5, 1] #=\> [] a[5..10] #=\> []
slice(index) slice(start, length) slice(range)
161
Deletes the element(s) given by an index (optionally up to length elements) or by a range. Returns the deleted object (or objects), or nil if the index is out of range. a = ["a", "b", "c"] a.slice!(1) #=\> "b" a #=\> ["a", "c"] a.slice!(-1) #=\> "c" a #=\> ["a"] a.slice!(100) #=\> nil a #=\> ["a"]
slice!(index) slice!(start, length) slice!(range)
162
Returns a new array created by sorting self. Comparisons for the sort will be done using the operator or using an optional code block. The block must implement a comparison between a and b, and return -1, when a follows b, 0 when a and b are equivalent, or +1 if b follows a. See also Enumerable#sort\_by. a = ["d", "a", "e", "c", "b"] a.sort #=\> ["a", "b", "c", "d", "e"] a.sort { |x,y| y x } #=\> ["e", "d", "c", "b", "a"]
sort sort { |a, b| block }
163
Sorts self in place. Comparisons for the sort will be done using the operator or using an optional code block. The block must implement a comparison between a and b, and return -1, when a follows b, 0 when a and b are equivalent, or +1 if b follows a. See also Enumerable#sort\_by. a = ["d", "a", "e", "c", "b"] a.sort! #=\> ["a", "b", "c", "d", "e"] a.sort! { |x,y| y x } #=\> ["e", "d", "c", "b", "a"]
sort! sort! { |a, b| block }
164
Sorts self in place using a set of keys generated by mapping the values in self through the given block. If no block is given, an Enumerator is returned instead.
sort\_by! { |obj| block } sort\_by!
165
Returns first n elements from the array. If a negative number is given, raises an ArgumentError. See also #drop a = [1, 2, 3, 4, 5, 0] a.take(3) #=\> [1, 2, 3]
take(n)
166
Passes elements to the block until the block returns nil or false, then stops iterating and returns an array of all prior elements. If no block is given, an Enumerator is returned instead. See also #drop\_while a = [1, 2, 3, 4, 5, 0] a.take\_while { |i| i \< 3 } #=\> [1, 2]
take\_while { |arr| block } take\_while
167
Returns self. If called on a subclass of Array, converts the receiver to an Array object.
to\_a
168
Assumes that self is an array of arrays and transposes the rows and columns. a = [[1,2], [3,4], [5,6]] a.transpose #=\> [[1, 3, 5], [2, 4, 6]] If the length of the subarrays don’t match, an IndexError is raised.
transpose
169
Returns a new array by removing duplicate values in self. If a block is given, it will use the return value of the block for comparison. It compares values using their hash and eql? methods for efficiency. a = ["a", "a", "b", "b", "c"] a.uniq # =\> ["a", "b", "c"] b = [["student","sam"], ["student","george"], ["teacher","matz"]] b.uniq { |s| s.first } # =\> [["student", "sam"], ["teacher", "matz"]]
uniq uniq { |item| ... }
170
Removes duplicate elements from self. If a block is given, it will use the return value of the block for comparison. It compares values using their hash and eql? methods for efficiency. Returns nil if no changes are made (that is, no duplicates are found). a = ["a", "a", "b", "b", "c"] a.uniq! # =\> ["a", "b", "c"] b = ["a", "b", "c"] b.uniq! # =\> nil c = [["student","sam"], ["student","george"], ["teacher","matz"]] c.uniq! { |s| s.first } # =\> [["student", "sam"], ["teacher", "matz"]]
uniq! uniq! { |item| ... }
171
Prepends objects to the front of self, moving other elements upwards. See also #shift for the opposite effect. a = ["b", "c", "d"] a.unshift("a") #=\> ["a", "b", "c", "d"] a.unshift(1, 2) #=\> [1, 2, "a", "b", "c", "d"]
unshift(obj, ...)
172
Returns an array containing the elements in self corresponding to the given selector(s). The selectors may be either integer indices or ranges. See also #select. a = %w{ a b c d e f } a.values\_at(1, 3, 5) # =\> ["b", "d", "f"] a.values\_at(1, 3, 5, 7) # =\> ["b", "d", "f", nil] a.values\_at(-1, -2, -2, -7) # =\> ["f", "e", "e", nil] a.values\_at(4..6, 3...6) # =\> ["e", "f", nil, "d", "e", "f"]
values\_at(selector, ...)
173
Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument. This generates a sequence of ary.size n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than the size of the initial array, nil values are supplied. If a block is given, it is invoked for each output array, otherwise an array of arrays is returned. a = [4, 5, 6] b = [7, 8, 9] [1, 2, 3].zip(a, b) #=\> [[1, 4, 7], [2, 5, 8], [3, 6, 9]] [1, 2].zip(a, b) #=\> [[1, 4, 7], [2, 5, 8]] a.zip([1, 2], [8]) #=\> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]
zip(arg, ...) zip(arg, ...) { |arr| block }
174
Set Union — Returns a new array by joining ary with other\_ary, excluding any duplicates and preserving the order from the original array. It compares elements using their hash and eql? methods for efficiency. ["a", "b", "c"] | ["c", "d", "a"] #=\> ["a", "b", "c", "d"] See also #uniq.
ary | other\_ary