Netskin Logo

Ruby arrays cheatsheet

#ruby
by Thomas Rudolf on 29.08.2022

This little cheat sheet does not claim to be comprehensive, but is rather meant to shine some light one less known array methods that might come in handy in every day coding situations.

Creating arrays

Let’s start with initializing an array, optionally with initial values:

a = Array.new(5)
# => [nil, nil, nil, nil, nil]
a = Array.new(5, "n/a")
# => ["n/a", "n/a", "n/a", "n/a", "n/a"]
a = Array.new(3){ |i| "Value at index #{i}" }
a = ["Value at index 0", "Value at index 1",  "Value at index 2"]
a = Array(1..5)
# => [1,2,3,4,5]

There are a few more “shortcuts” specifically for creating arrays of strings or symbols.

a = %w(this creates an array of strings)
# => ["this", "creates", "an", "array", "of", "strings"]
a = %i(this creates an array of symbols)
# => [:this, :creates, :an, :array, :of, :symbols]

Instead of parentheses ( ) any kind of non-alpha numeric character can be used as delimiter, e.g.

%i|works just the same|
%w<or this>
%i;or even this;

Manipulating an array

Besides the most commonly used ways to manipulate an array, there are a few less common but very handy ways to interact with a Ruby array.

Adding to or removing from an array

Sometimes it comes in handy to add the content of a different array to an array, that can be done like so:

[1,2,3].concat([4,5,6])
# => [1,2,3,4,5,6]

We can also fill an array with an object, optionally specifying the start index and the length (not end index), this can be useful e.g. if you have a fixed length array and want to set certain indices to nil:

[1,2,3,4,5].fill(nil, 2, 2)
# => [1,2,nil,nil,5]

There’s .push & .pop, .shift & .unshift to either add/remove elements from the end of the array or the beginning, respectively, and return the element if the command removes it from either front or end.

a = [1,2,3,4,5]
a.push(6) # this is equivalent to a << 6
# => [1,2,3,4,5,6]
[1,2,3,4,5,6].pop
# => 6
a
# => [1,2,3,4,5]

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

Transforming arrays

Everybody knows about .sort, .uniq or .flatten, but the following ones can also be quite useful and are probably less known:

a = [1,2,3,4,5]

a.shuffle # returns a new array with the content of the original array randomly shuffled
# => [2, 5, 1, 4, 3]
a.rotate(2) # returns a new array, where the elements are rotated by 2 steps
# => [3, 4, 5, 1, 2]
a.reverse # returns a new array, with the elements in reverse order
# => [5, 4, 3, 2, 1]

All of the above methods to rearrange the array content can be used as bang methods as well, mutating the original array

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

Some more handy methods

A nifty way to do a performant search on a large, sorted array is to use .bsearch, which uses binary search, so you have O(log n). The method accepts a block that specifies the search condition and returns the first element that matches.

a = [1,2,3,4,5]
a.bsearch{ |x| x > 3 }
# => 4

The method .hash returns an integer hash code of a given hash, so it can be used to quickly check for equality:

[1,2,3].hash
# => 4193003645009831240
[1,2,3].hash == [3,2,1].hash
# => false
[1,2,3].hash == [1,2,3].hash
# => true

With .zip we can intertwine a pair of arrays:

a = [1,2,3]
# => [1, 2, 3]
b = ["a", "b", "c"]
# => ["a", "b", "c"]
a.zip(b)
# => [[1, "a"], [2, "b"], [3, "c"]]

As already mentioned, these are just a few selected methods on ruby’s array that I find interesting and helpful. A comprehensive list and further reading can be found in the Ruby documentation

Happy Coding!

❮ RSpec Quick Tip - be_done?
Calculate Age in Ruby on Rails ❯
Netskin Logo