Unique Ruby Array Methods

Richard Chea
2 min readDec 27, 2020

--

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.

.transpose

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 ],
["red","blue","yellow","green","orange"]
]
array.transpose
# => [
# ["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.

.fill

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

.sample

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"
array.sample(2)
# => ["b", "e"]

.flatten

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.

http://www.ruby-doc.org/core-2.1.2/Array.html

--

--

No responses yet