Unique Ruby Array Methods

Arrays can be manipulated with Ruby methods and some common ones are .length, . shift, .reverse, and .push. We’re going to go over a few unique methods that can be quite useful in certain situations.


The transpose method is quite unique in what it does. It essentially allows you to take rows and convert them into columns.

array = [
[ "a", "b", "c", "d", "e" ],
[ 1, 2, 3, 4, 5 ],
# => [
# ["a", 1, "red" ],
# ["b", 2, "blue" ],
# ["c", 3, "yellow" ],
# ["d", 4, "green" ],
# ["e", 5, "orange"]
# ]

As you can see from the example, it gathers the first row of letters and converts it to the first element of the arrays, the numbers to the second element of the arrays, and the colors to the third element of the arrays.


The fill method will fill every element in an array with the argument that’s passed to it.

%w{ a b c }.fill("Hi!")# => ["Hi!", "Hi!", "Hi!"]


The sample method will randomly select one or more elements from the array. By default, it will return one element from the array unless you specify the number of elements.

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


The flatten method will turn a nested array into an array that is one level deep. It also takes an

array1 = [[1, 2], [3, [4]], [[[5]]]]array1.flatten
# => [1, 2, 3, 4, 5]
array2 = [[[1], 2]]array2.flatten(1)
#=> [[1], 2]

These are a few unique methods that can be used on arrays. Read the Ruby documentation for info and other unique methods to play around with.