Class: Array

Inherits:
NSMutableArray show all
Includes:
Enumerable

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods included from Enumerable

#_count, #all?, #any?, #collect_concat, #detect, #each_cons, #each_entry, #each_slice, #each_with_index, #each_with_object, #entries, #find, #find_all, #flat_map, #grep, #group_by, #inject, #max, #max_by, #member?, #min, #min_by, #minmax, #minmax_by, #none?, #one?, #partition, #reduce, #sort_by

Methods inherited from NSMutableArray

#addObject:, #addObjectsFromArray:, arrayWithCapacity:, #exchangeObjectAtIndex:withObjectAtIndex:, #filterUsingPredicate:, #initWithCapacity:, #insertObject:atIndex:, #insertObjects:atIndexes:, #removeAllObjects, #removeLastObject, #removeObject:, #removeObject:inRange:, #removeObjectAtIndex:, #removeObjectIdenticalTo:, #removeObjectIdenticalTo:inRange:, #removeObjectsAtIndexes:, #removeObjectsInArray:, #removeObjectsInRange:, #replaceObjectAtIndex:withObject:, #replaceObjectsAtIndexes:withObjects:, #replaceObjectsInRange:withObjectsFromArray:, #replaceObjectsInRange:withObjectsFromArray:range:, #setArray:, #setObject:atIndexedSubscript:, #sortUsingComparator:, #sortUsingDescriptors:, #sortUsingFunction:context:, #sortUsingSelector:, #sortWithOptions:usingComparator:

Methods inherited from NSArray

#addObserver:forKeyPath:options:context:, #addObserver:toObjectsAtIndexes:forKeyPath:options:context:, array, #arrayByAddingObject:, #arrayByAddingObjectsFromArray:, arrayWithArray:, arrayWithContentsOfFile:, arrayWithContentsOfURL:, arrayWithObject:, arrayWithObjects:, arrayWithObjects:count:, #componentsJoinedByString:, #containsObject:, #description, #descriptionWithLocale:, #descriptionWithLocale:indent:, #enumerateObjectsAtIndexes:options:usingBlock:, #enumerateObjectsUsingBlock:, #enumerateObjectsWithOptions:usingBlock:, #filteredArrayUsingPredicate:, #firstObjectCommonWithArray:, #getObjects:range:, #indexOfObject:, #indexOfObject:inRange:, #indexOfObject:inSortedRange:options:usingComparator:, #indexOfObjectAtIndexes:options:passingTest:, #indexOfObjectIdenticalTo:, #indexOfObjectIdenticalTo:inRange:, #indexOfObjectPassingTest:, #indexOfObjectWithOptions:passingTest:, #indexesOfObjectsAtIndexes:options:passingTest:, #indexesOfObjectsPassingTest:, #indexesOfObjectsWithOptions:passingTest:, #initWithArray:, #initWithArray:copyItems:, #initWithContentsOfFile:, #initWithContentsOfURL:, #initWithObjects:, #initWithObjects:count:, #isEqualToArray:, #lastObject, #makeObjectsPerformSelector:, #makeObjectsPerformSelector:withObject:, #objectAtIndex:, #objectAtIndexedSubscript:, #objectEnumerator, #objectsAtIndexes:, #pathsMatchingExtensions:, #removeObserver:forKeyPath:, #removeObserver:forKeyPath:context:, #removeObserver:fromObjectsAtIndexes:forKeyPath:, #removeObserver:fromObjectsAtIndexes:forKeyPath:context:, #reverseObjectEnumerator, #setValue:forKey:, #sortedArrayHint, #sortedArrayUsingComparator:, #sortedArrayUsingDescriptors:, #sortedArrayUsingFunction:context:, #sortedArrayUsingFunction:context:hint:, #sortedArrayUsingSelector:, #sortedArrayWithOptions:usingComparator:, #subarrayWithRange:, #valueForKey:, #writeToFile:atomically:, #writeToURL:atomically:

Methods inherited from NSObject

#!, #!=, #!~, #===, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #enum_for, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_dup, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version

Constructor Details

- (Object) new(size = 0, obj = nil) - (Object) new(array) - (Object) new(size) {|index| ... }

Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element's index to the given block and storing the return value.

Array.new
Array.new(2)
Array.new(5, "A")

# only one copy of the object is created
a = Array.new(2, Hash.new)
a[0]['cat'] = 'feline'
a
a[1]['cat'] = 'Felix'
a

# here multiple copies are created
a = Array.new(2) { Hash.new }
a[0]['cat'] = 'feline'
a

squares = Array.new(5) {|i| i*i}
squares

copy = Array.new(squares)

Overloads:

  • - new {|index| ... }

    Yields:

    • (index)

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class NSObject

Class Method Details

+ (Object) []

Returns a new array populated with the given objects.

Array.[]( 1, 'a', /^A/ )
Array[ 1, 'a', /^A/ ]
[ 1, 'a', /^A/ ]

+ (Object) alloc

+ (Object) new

+ (Array?) try_convert(obj)

Try to convert obj into an array, using to_ary method. Returns converted array or nil if obj cannot be converted for any reason. This method can be used to check if an argument is an array.

Array.try_convert([1])   #=> [1]
Array.try_convert("1")   #=> nil

if tmp = Array.try_convert(arg)
  # the argument is an array
elsif tmp = String.try_convert(arg)
  # the argument is a string
end

Returns:

Instance Method Details

- (Array) &(other_ary)

Set Intersection---Returns a new array containing elements common to the two arrays, with no duplicates.

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]

Returns:

- (Array) *(int) - (Object) *(str)

Repetition---With a String argument, equivalent to self.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"

Overloads:

- (Array) +(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 ]

Returns:

- (Array) -(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. (If you need set-like behavior, see the library class Set.)

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]

Returns:

- (Array) <<(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 ] ]

Returns:

- (-1, ...) <=>(other_ary)

Comparison---Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other_ary. Each object in each array is compared (using ). If any value isn't equal, then that inequality is the return value. If all the values found 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

Returns:

  • (-1, 0, +1, nil)

- (Boolean) ==(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 the other array.

[ "a", "c" ]    == [ "a", "c", 7 ]     #=> false
[ "a", "c", 7 ] == [ "a", "c", 7 ]     #=> true
[ "a", "c", 7 ] == [ "a", "d", "f" ]   #=> false

Returns:

  • (Boolean)

- (Object?) [](index) - (Array?) [](start, length) - (Array?) [](range) - (Object?) slice(index) - (Array?) slice(start, length) - (Array?) slice(range)

Element Reference---Returns the element at index, or returns a subarray starting at start and continuing for length elements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). 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[5, 1]                #=> []
a[5..10]               #=> []

Overloads:

  • - []

    Returns:

  • - []

    Returns:

  • - []

    Returns:

  • - slice

    Returns:

  • - slice

    Returns:

  • - slice

    Returns:

- (Object) []=(index) - (Object?) []=(start, length) - (Object?) []=(range)

Element Assignment---Sets the element at index, or replaces a subarray starting at start and continuing for length elements, or replaces a subarray specified by range. If indices are greater than the current capacity of the array, the array grows automatically. A negative indices will count backward from the end of the array. Inserts elements if length is zero. An IndexError is raised if a negative index points past the beginning of the array. See also Array#push, and Array#unshift.

a = Array.new
a[4] = "4";                 #=> [nil, nil, nil, nil, "4"]
a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"]
a[1..2] = [ 1, 2 ]          #=> ["a", 1, 2, nil, "4"]
a[0, 2] = "?"               #=> ["?", 2, nil, "4"]
a[0..2] = "A"               #=> ["A", "4"]
a[-1]   = "Z"               #=> ["A", "Z"]
a[1..-1] = nil              #=> ["A", nil]
a[1..-1] = []               #=> ["A"]

Overloads:

- (Array?) 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 Array#rassoc.

s1 = [ "colors", "red", "blue", "green" ]
s2 = [ "letters", "a", "b", "c" ]
s3 = "foo"
a  = [ s1, s2, s3 ]
a.assoc("letters")  #=> [ "letters", "a", "b", "c" ]
a.assoc("foo")      #=> nil

Returns:

- (Object?) 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"

Returns:

- (Array) clear

Removes all elements from self.

a = [ "a", "b", "c", "d", "e" ]
a.clear    #=> [ ]

Returns:

- (Array) collect {|item| ... } - (Array) map {|item| ... } - (Enumerator) collect - (Enumerator) map

Invokes 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.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]

Overloads:

  • - collect {|item| ... }

    Yields:

    • (item)

    Returns:

  • - map {|item| ... }

    Yields:

    • (item)

    Returns:

  • - collect

    Returns:

  • - map

    Returns:

- (Array) collect! {|item| ... } - (Array) map! {|item| ... } - (Enumerator) collect! - (Enumerator) map!

Invokes the block once for each element of self, replacing the element with the value returned by block. See also Enumerable#collect.

If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect! {|x| x + "!" }
a             #=>  [ "a!", "b!", "c!", "d!" ]

Overloads:

  • - collect! {|item| ... }

    Yields:

    • (item)

    Returns:

  • - map! {|item| ... }

    Yields:

    • (item)

    Returns:

  • - collect!

    Returns:

  • - map!

    Returns:

- (Array) combination(n) {|c| ... } - (Enumerator) combination(n)

When invoked with a block, yields all combinations of length n of elements from ary and then returns ary 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

Overloads:

  • - combination {|c| ... }

    Yields:

    • (c)

    Returns:

  • - combination

    Returns:

- (Array) compact

Returns a copy of self with all nil elements removed.

[ "a", nil, "b", nil, "c", nil ].compact
                  #=> [ "a", "b", "c" ]

Returns:

- (Array?) compact!

Removes nil elements from the array. Returns nil if no changes were made, otherwise returns ary.

[ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
[ "a", "b", "c" ].compact!           #=> nil

Returns:

- (Array) concat(other_ary)

Appends the elements of other_ary to self.

[ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ]

Returns:

- (Integer) count - (Integer) count(obj) - (Integer) count {|item| ... }

Returns the number of elements. If an argument is given, counts the number of elements which equals to obj. If a block is given, counts the number of elements yielding a true value.

ary = [1, 2, 4, 2]
ary.count             #=> 4
ary.count(2)          #=> 2
ary.count{|x|x%2==0}  #=> 3

Overloads:

  • - count

    Returns:

  • - count

    Returns:

  • - count {|item| ... }

    Yields:

    • (item)

    Returns:

- (nil) cycle(n = nil) {|obj| ... } - (Enumerator) cycle(n = nil)

Calls block for each element repeatedly n times or forever if none or nil is given. If a non-positive number is given or the array is empty, does nothing. 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.

Overloads:

  • - cycle {|obj| ... }

    Yields:

    • (obj)

    Returns:

    • (nil)
  • - cycle

    Returns:

- (Object?) delete(obj) - (Object?) delete(obj) { ... }

Deletes items from self that are equal to obj. If any items are found, returns obj. If the item is not found, returns nil. If the optional code block is given, returns the result of block 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"

Overloads:

  • - delete

    Returns:

  • - delete { ... }

    Yields:

    Returns:

- (Object?) delete_at(index)

Deletes the element at the specified index, returning that element, or nil if the index is out of range. See also Array#slice!.

a = %w( ant bat cat dog )
a.delete_at(2)    #=> "cat"
a                 #=> ["ant", "bat", "dog"]
a.delete_at(99)   #=> nil

Returns:

- (Array) delete_if {|item| ... } - (Enumerator) delete_if

Deletes every element of self for which block evaluates to true. The array is changed instantly every time the block is called and not after the iteration is over. See also Array#reject!

If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c" ]
a.delete_if {|x| x >= "b" }   #=> ["a"]

Overloads:

  • - delete_if {|item| ... }

    Yields:

    • (item)

    Returns:

  • - delete_if

    Returns:

- (Array) drop(n)

Drops first n elements from ary and returns the rest of the elements in an array.

a = [1, 2, 3, 4, 5, 0]
a.drop(3)             #=> [4, 5, 0]

Returns:

- (Array) drop_while {|arr| ... } - (Enumerator) drop_while

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.

a = [1, 2, 3, 4, 5, 0]
a.drop_while {|i| i < 3 }   #=> [3, 4, 5, 0]

Overloads:

  • - drop_while {|arr| ... }

    Yields:

    • (arr)

    Returns:

  • - drop_while

    Returns:

- (Object) dup

:nodoc:

- (Array) each {|item| ... } - (Enumerator) each

Calls block once for each element in self, passing that element as a parameter.

If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c" ]
a.each {|x| print x, " -- " }

produces:

a -- b -- c --

Overloads:

  • - each {|item| ... }

    Yields:

    • (item)

    Returns:

  • - each

    Returns:

- (Array) each_index {|index| ... } - (Enumerator) each_index

Same as Array#each, but passes the index of the element instead of the element itself.

If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c" ]
a.each_index {|x| print x, " -- " }

produces:

0 -- 1 -- 2 --

Overloads:

  • - each_index {|index| ... }

    Yields:

    • (index)

    Returns:

  • - each_index

    Returns:

- (Boolean) empty?

Returns true if self contains no elements.

[].empty?   #=> true

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Boolean) ==(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 the other array.

[ "a", "c" ]    == [ "a", "c", 7 ]     #=> false
[ "a", "c", 7 ] == [ "a", "c", 7 ]     #=> true
[ "a", "c", 7 ] == [ "a", "d", "f" ]   #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Object) fetch(index) - (Object) fetch(index, default) - (Object) fetch(index) {|index| ... }

Tries to return the element at position index. If the index lies outside the array, the first form throws an IndexError exception, the second form returns default, and the third form returns the value of invoking the block, passing in the index. 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(4) { |i| i*i }   #=> 16

Overloads:

  • - fetch

    Returns:

  • - fetch

    Returns:

  • - fetch {|index| ... }

    Yields:

    • (index)

    Returns:

- (Array) fill(obj) - (Array) fill(obj, start[, length]) - (Array) fill(obj, range) - (Array) fill {|index| ... } - (Array) fill(start[, length]) {|index| ... } - (Array) fill(range) {|index| ... }

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 self.length. The last three forms fill the array with the value of the block. The block is passed the absolute index of each element to be filled. Negative values of start count from the end of the array.

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]

Overloads:

  • - fill

    Returns:

  • - fill

    Returns:

  • - fill

    Returns:

  • - fill {|index| ... }

    Yields:

    • (index)

    Returns:

  • - fill {|index| ... }

    Yields:

    • (index)

    Returns:

  • - fill {|index| ... }

    Yields:

    • (index)

    Returns:

- (Integer?) index(obj) - (Integer?) index {|item| ... } - (Enumerator) index

Returns the index of the first object in self such that the object is == to obj. If a block is given instead of an argument, returns index of first object for which block is true. Returns nil if no match is found. See also Array#rindex.

If neither block nor argument is given, an enumerator is returned instead.

a = [ "a", "b", "c" ]
a.index("b")        #=> 1
a.index("z")        #=> nil
a.index{|x|x=="b"}  #=> 1

This is an alias of #find_index.

Overloads:

  • - index

    Returns:

  • - index {|item| ... }

    Yields:

    • (item)

    Returns:

  • - index

    Returns:

- (Object?) first - (Array) 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.

a = [ "q", "r", "s", "t" ]
a.first     #=> "q"
a.first(2)  #=> ["q", "r"]

Overloads:

  • - first

    Returns:

  • - first

    Returns:

- (Array) flatten - (Array) flatten(level)

Returns a new array that is a one-dimensional flattening of this array (recursively). That is, for every element that is an array, extract its elements into the new array. If the optional level argument determines the level of recursion to flatten.

s = [ 1, 2, 3 ]           #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ]   #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ]       #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten(1)              #=> [1, 2, 3, [4, 5]]

Overloads:

  • - flatten

    Returns:

  • - flatten

    Returns:

- (Array?) flatten! - (Array?) flatten!(level)

Flattens self in place. Returns nil if no modifications were made (i.e., ary contains no subarrays.) If 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]]

Overloads:

  • - flatten!

    Returns:

  • - flatten!

    Returns:

- (Fixnum) 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?).

Returns:

- (Boolean) include?(obj)

Returns true if the given object is present in self (that is, if any object == anObject), false otherwise.

a = [ "a", "b", "c" ]
a.include?("b")   #=> true
a.include?("z")   #=> false

Returns:

  • (Boolean)

Returns:

  • (Boolean)

- (Integer?) index(obj) - (Integer?) index {|item| ... } - (Enumerator) index

Returns the index of the first object in self such that the object is == to obj. If a block is given instead of an argument, returns index of first object for which block is true. Returns nil if no match is found. See also Array#rindex.

If neither block nor argument is given, an enumerator is returned instead.

a = [ "a", "b", "c" ]
a.index("b")        #=> 1
a.index("z")        #=> nil
a.index{|x|x=="b"}  #=> 1

This is an alias of #find_index.

Overloads:

  • - index

    Returns:

  • - index {|item| ... }

    Yields:

    • (item)

    Returns:

  • - index

    Returns:

- (Array) 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"]

Returns:

- (Array) insert(index, obj...)

Inserts the given values before the element with the given index (which may be negative).

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

Returns:

- (String) to_s - (String) inspect

Creates a string representation of self.

Overloads:

- (String) join(sep = $,)

Returns a string created by converting each element of the array to a string, separated by sep.

[ "a", "b", "c" ].join        #=> "abc"
[ "a", "b", "c" ].join("-")   #=> "a-b-c"

Returns:

- (Array) keep_if {|item| ... } - (Enumerator) keep_if

Deletes every element of self for which block evaluates to false. See also Array#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"]

Overloads:

  • - keep_if {|item| ... }

    Yields:

    • (item)

    Returns:

  • - keep_if

    Returns:

- (Object?) last - (Array) last(n)

Returns the last element(s) of self. If the array is empty, the first form returns nil.

a = [ "w", "x", "y", "z" ]
a.last     #=> "z"
a.last(2)  #=> ["y", "z"]

Overloads:

  • - last

    Returns:

  • - last

    Returns:

- (Integer) length

Returns the number of elements in self. May be zero.

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

Returns:

- (Array) collect {|item| ... } - (Array) map {|item| ... } - (Enumerator) collect - (Enumerator) map

Invokes 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.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]

Overloads:

  • - collect {|item| ... }

    Yields:

    • (item)

    Returns:

  • - map {|item| ... }

    Yields:

    • (item)

    Returns:

  • - collect

    Returns:

  • - map

    Returns:

- (Array) collect! {|item| ... } - (Array) map! {|item| ... } - (Enumerator) collect! - (Enumerator) map!

Invokes the block once for each element of self, replacing the element with the value returned by block. See also Enumerable#collect.

If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect! {|x| x + "!" }
a             #=>  [ "a!", "b!", "c!", "d!" ]

Overloads:

  • - collect! {|item| ... }

    Yields:

    • (item)

    Returns:

  • - map! {|item| ... }

    Yields:

    • (item)

    Returns:

  • - collect!

    Returns:

  • - map!

    Returns:

- (Object) pack

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"

Directives for pack.

Integer      | Array   |
Directive    | Element | Meaning
---------------------------------------------------------------------------
   C         | Integer | 8-bit unsigned (unsigned char)
   S         | Integer | 16-bit unsigned, native endian (uint16_t)
   L         | Integer | 32-bit unsigned, native endian (uint32_t)
   Q         | Integer | 64-bit unsigned, native endian (uint64_t)
             |         |
   c         | Integer | 8-bit signed (signed char)
   s         | Integer | 16-bit signed, native endian (int16_t)
   l         | Integer | 32-bit signed, native endian (int32_t)
   q         | Integer | 64-bit signed, native endian (int64_t)
             |         |
   S_, S!    | Integer | unsigned short, native endian
   I, I_, I! | Integer | unsigned int, native endian
   L_, L!    | Integer | unsigned long, native endian
             |         |
   s_, s!    | Integer | signed short, native endian
   i, i_, i! | Integer | signed int, native endian
   l_, l!    | Integer | signed long, native endian
             |         |
   S> L> Q>  | Integer | same as the directives without ">" except
   s> l> q>  |         | big endian
   S!> I!>   |         | (available since Ruby 1.9.3)
   L!>       |         | "S>" is same as "n"
   s!> i!>   |         | "L>" is same as "N"
   l!>       |         |
             |         |
   S< L< Q<  | Integer | same as the directives without "<" except
   s< l< q<  |         | little endian
   S!< I!<   |         | (available since Ruby 1.9.3)
   L!<       |         | "S<" is same as "v"
   s!< i!<   |         | "L<" is same as "V"
   l!<       |         |
             |         |
   n         | Integer | 16-bit unsigned, network (big-endian) byte order
   N         | Integer | 32-bit unsigned, network (big-endian) byte order
   v         | Integer | 16-bit unsigned, VAX (little-endian) byte order
   V         | Integer | 32-bit unsigned, VAX (little-endian) byte order
             |         |
   U         | Integer | UTF-8 character
   w         | Integer | BER-compressed integer

Float        |         |
Directive    |         | Meaning
---------------------------------------------------------------------------
   D, d      | Float   | double-precision, native format
   F, f      | Float   | single-precision, native format
   E         | Float   | double-precision, little-endian byte order
   e         | Float   | single-precision, little-endian byte order
   G         | Float   | double-precision, network (big-endian) byte order
   g         | Float   | single-precision, network (big-endian) byte order

String       |         |
Directive    |         | Meaning
---------------------------------------------------------------------------
   A         | String  | arbitrary binary string (space padded, count is width)
   a         | String  | arbitrary binary string (null padded, count is width)
   Z         | String  | same as ``a'', except that null is added with *
   B         | String  | bit string (MSB first)
   b         | String  | bit string (LSB first)
   H         | String  | hex string (high nibble first)
   h         | String  | hex string (low nibble first)
   u         | String  | UU-encoded string
   M         | String  | quoted printable, MIME encoding (see RFC2045)
   m         | String  | base64 encoded string (see RFC 2045, count is width)
             |         | (if count is 0, no line feed are added, see RFC 4648)
   P         | String  | pointer to a structure (fixed-length string)
   p         | String  | pointer to a null-terminated string

Misc.        |         |
Directive    |         | Meaning
---------------------------------------------------------------------------
   @         | ---     | moves to absolute position
   X         | ---     | back up a byte
   x         | ---     | null byte

- (Array) permutation {|p| ... } - (Enumerator) permutation - (Array) permutation(n) {|p| ... } - (Enumerator) permutation(n)

When invoked with a block, yield all permutations of length n of the elements of ary, 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

Overloads:

  • - permutation {|p| ... }

    Yields:

    • (p)

    Returns:

  • - permutation

    Returns:

  • - permutation {|p| ... }

    Yields:

    • (p)

    Returns:

  • - permutation

    Returns:

- (Object?) pop - (Array) 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.

a = [ "a", "b", "c", "d" ]
a.pop     #=> "d"
a.pop(2)  #=> ["b", "c"]
a         #=> ["a"]

Overloads:

- (Array) product(other_ary, ...) - (Array) product(other_ary, ...) {|p| ... }

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([])          #=> []

Overloads:

  • - product

    Returns:

  • - product {|p| ... }

    Yields:

    • (p)

    Returns:

- (Array) 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.

a = [ "a", "b", "c" ]
a.push("d", "e", "f")
        #=> ["a", "b", "c", "d", "e", "f"]

Returns:

- (Array?) rassoc(obj)

Searches through the array whose elements are also arrays. Compares obj with the second element of each contained array using ==. Returns the first contained array that matches. See also Array#assoc.

a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
a.rassoc("two")    #=> [2, "two"]
a.rassoc("four")   #=> nil

Returns:

- (Array) reject {|item| ... } - (Enumerator) reject

Returns a new array containing the items in self for which the block is not true. See also Array#delete_if

If no block is given, an enumerator is returned instead.

Overloads:

  • - reject {|item| ... }

    Yields:

    • (item)

    Returns:

  • - reject

    Returns:

- (Array?) reject! {|item| ... } - (Enumerator) reject!

Equivalent to Array#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 and not after the iteration is over. See also Enumerable#reject and Array#delete_if.

If no block is given, an enumerator is returned instead.

Overloads:

  • - reject! {|item| ... }

    Yields:

    • (item)

    Returns:

  • - reject!

    Returns:

- (Array) 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"]

Returns:

- (Array) reverse

Returns a new array containing self's elements in reverse order.

[ "a", "b", "c" ].reverse   #=> ["c", "b", "a"]
[ 1 ].reverse               #=> [1]

Returns:

- (Array) reverse!

Reverses self in place.

a = [ "a", "b", "c" ]
a.reverse!       #=> ["c", "b", "a"]
a                #=> ["c", "b", "a"]

Returns:

- (Array) reverse_each {|item| ... } - (Enumerator) reverse_each

Same as Array#each, but traverses self in reverse order.

a = [ "a", "b", "c" ]
a.reverse_each {|x| print x, " " }

produces:

c b a

Overloads:

  • - reverse_each {|item| ... }

    Yields:

    • (item)

    Returns:

  • - reverse_each

    Returns:

- (Integer?) rindex(obj) - (Integer?) rindex {|item| ... } - (Enumerator) rindex

Returns the index of the last object in self == to obj. If a block is given instead of an argument, returns index of first object for which block is true, starting from the last object. Returns nil if no match is found. See also Array#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

Overloads:

  • - rindex

    Returns:

  • - rindex {|item| ... }

    Yields:

    • (item)

    Returns:

  • - rindex

    Returns:

- (Array) rotate(cnt = 1)

Returns new array by rotating self so that the element at cnt in self is the first element of the new array. If cnt is negative then it rotates in the opposite direction.

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

Returns:

- (Array) rotate!(cnt = 1)

Rotates self in place so that the element at cnt comes first, and returns self. If cnt is negative then it rotates in the opposite direction.

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

Returns:

- (Object) sample - (Array) sample(n)

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.

Overloads:

- (Array) select {|item| ... } - (Enumerator) select

Invokes the block passing in successive elements from self, returning an array containing those elements for which the block returns a true value (equivalent to Enumerable#select).

If no block is given, an enumerator is returned instead.

a = %w{ a b c d e f }
a.select {|v| v =~ /[aeiou]/}   #=> ["a", "e"]

Overloads:

  • - select {|item| ... }

    Yields:

    • (item)

    Returns:

  • - select

    Returns:

- (Array?) select! {|item| ... } - (Enumerator) select!

Invokes the block passing in successive elements from self, deleting elements for which the block returns a false value. It returns self if changes were made, otherwise it returns nil. See also Array#keep_if

If no block is given, an enumerator is returned instead.

Overloads:

  • - select! {|item| ... }

    Yields:

    • (item)

    Returns:

  • - select!

    Returns:

- (Object?) shift - (Array) shift(n)

Returns the first element of self and removes 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.

args = [ "-m", "-q", "filename" ]
args.shift     #=> "-m"
args           #=> ["-q", "filename"]

args = [ "-m", "-q", "filename" ]
args.shift(2)  #=> ["-m", "-q"]
args           #=> ["filename"]

Overloads:

  • - shift

    Returns:

  • - shift

    Returns:

- (Array) shuffle

Returns a new array with elements of this array shuffled.

a = [ 1, 2, 3 ]           #=> [1, 2, 3]
a.shuffle                 #=> [2, 3, 1]

Returns:

- (Array) shuffle!

Shuffles elements in self in place.

Returns:

- (Integer) length

Returns the number of elements in self. May be zero.

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

Returns:

- (Object?) [](index) - (Array?) [](start, length) - (Array?) [](range) - (Object?) slice(index) - (Array?) slice(start, length) - (Array?) slice(range)

Element Reference---Returns the element at index, or returns a subarray starting at start and continuing for length elements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). 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[5, 1]                #=> []
a[5..10]               #=> []

Overloads:

  • - []

    Returns:

  • - []

    Returns:

  • - []

    Returns:

  • - slice

    Returns:

  • - slice

    Returns:

  • - slice

    Returns:

- (Object?) slice!(index) - (Array?) slice!(start, length) - (Array?) slice!(range)

Deletes the element(s) given by an index (optionally with a length) 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"]

Overloads:

  • - slice!

    Returns:

  • - slice!

    Returns:

  • - slice!

    Returns:

- (Array) sort - (Array) sort {|a, b| ... }

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 implements a comparison between a and b, returning -1, 0, or +1. 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"]

Overloads:

  • - sort

    Returns:

  • - sort {|a, b| ... }

    Yields:

    • (a, b)

    Returns:

- (Array) sort! - (Array) sort! {|a, b| ... }

Sorts self. Comparisons for the sort will be done using the operator or using an optional code block. The block implements a comparison between a and b, returning -1, 0, or +1. 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"]

Overloads:

  • - sort!

    Returns:

  • - sort! {|a, b| ... }

    Yields:

    • (a, b)

    Returns:

- (Array) sort_by! {|obj| ... } - (Enumerator) 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.

Overloads:

  • - sort_by! {|obj| ... }

    Yields:

    • (obj)

    Returns:

  • - sort_by!

    Returns:

- (Array) take(n)

Returns first n elements from ary.

a = [1, 2, 3, 4, 5, 0]
a.take(3)             #=> [1, 2, 3]

Returns:

- (Array) take_while {|arr| ... } - (Enumerator) 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.

a = [1, 2, 3, 4, 5, 0]
a.take_while {|i| i < 3 }   #=> [1, 2]

Overloads:

  • - take_while {|arr| ... }

    Yields:

    • (arr)

    Returns:

  • - take_while

    Returns:

- (Array) to_a

Returns self. If called on a subclass of Array, converts the receiver to an Array object.

Returns:

- (Array) to_a

Returns self. If called on a subclass of Array, converts the receiver to an Array object.

Returns:

- (String) to_s - (String) inspect

Creates a string representation of self.

Overloads:

- (Array) 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]]

Returns:

- (Array) uniq

Returns a new array by removing duplicate values in self.

a = [ "a", "a", "b", "b", "c" ]
a.uniq   #=> ["a", "b", "c"]
c = [ "a:def", "a:xyz", "b:abc", "b:xyz", "c:jkl" ]
c.uniq {|s| s[/^\w+/]}  #=> [ "a:def", "b:abc", "c:jkl" ]

Returns:

- (Array?) uniq!

Removes duplicate elements from self. 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 = [ "a:def", "a:xyz", "b:abc", "b:xyz", "c:jkl" ]
c.uniq! {|s| s[/^\w+/]}  #=> [ "a:def", "b:abc", "c:jkl" ]

Returns:

- (Array) unshift(obj, ...)

Prepends objects to the front of self, moving other elements upwards.

a = [ "b", "c", "d" ]
a.unshift("a")   #=> ["a", "b", "c", "d"]
a.unshift(1, 2)  #=> [ 1, 2, "a", "b", "c", "d"]

Returns:

- (Array) 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 Array#select.

a = %w{ a b c d e f }
a.values_at(1, 3, 5)
a.values_at(1, 3, 5, 7)
a.values_at(-1, -3, -5, -7)
a.values_at(1..3, 2...5)

Returns:

- (Array) zip(arg, ...) - (nil) zip(arg, ...) {|arr| ... }

Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument. This generates a sequence of self.size n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than enumObj.size, 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]]

Overloads:

  • - zip

    Returns:

  • - zip {|arr| ... }

    Yields:

    • (arr)

    Returns:

    • (nil)

- (Array) |(other_ary)

Set Union---Returns a new array by joining this array with other_ary, removing duplicates.

[ "a", "b", "c" ] | [ "c", "d", "a" ]
       #=> [ "a", "b", "c", "d" ]

Returns: