Ruby - Array Array Methods


Several of the standard array methods modify the array itself rather than returning a modified copy of the array.

These methods are marked with a terminating exclamation point, such as sort!, reverse!, flatten!, and compact!.

The << method modifies the array to its left by adding to it the array on its right.

clear method removes all the elements from the given array.

delete and delete_at remove selected elements.

The following table shows some of the more commonly used Array methods.

&Returns common elements of two arrays, no duplicates
+ Returns array concatenating two arrays
- Returns array with items in second array removed from first
<<Modifies first array by appending items from second array
clear Modifies array by removing all elements
compact Returns array with nil items removed
compact! Modifies array by removing nil items
delete( object ) Modifies array by deleting object
delete_at( index )Modifies array by deleting item at index
flatten Unpacks nested array items and returns array
flatten! Modifies array by unpacking nested array items
lengthReturns number of elements in array
reverse Returns array with elements in reverse order
reverse! Modifies array by reversing element order
sort Returns array sorted using <=>
sort! Modifies array sorted using <=>


arr1 = [1,1,2,2,3,3] 
arr2 = [1,2,3,4,5,6,7,8,9] # from   ww  w. j a v  a  2 s . com
arr3 = ['h','e','l','l','o',' ',nil,'w','o','r','l','d'] 

p(arr1&arr2 )           #=> [1, 2, 3] 
p(arr1+arr2)        #=> [1, 1, 2, 2, 3, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
p(arr1-arr2)        #=> [] 
p(arr2-arr1)        #=> [4, 5, 6, 7, 8, 9] 
p(arr1)                 #=> [1, 1, 2, 2, 3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]] 
p(arr1)                 #=>[]


An array is flattened when it contains no subarrays.

So if you have an array like [1,[2,3]], you can call [1,[2,3]].flatten to return this array: [1,2,3].

An array is said to be compacted when it contains no nil items.

So if you have an array like [1,2,nil,3], you can call [1,2,nil,3].compact to return this array: [1,2,3].

The methods of Array can be chained together by placing one method call directly after the other:

p( [1,nil,[2,nil,3]].flatten.compact ) #=> [1,2,3]