Useful Ruby Array Methods to Manage Your Data
By: Mahbub Zaman
Tags: Software Engineering, Programming, Ruby, Data Science, Productivity

The basics

Unlike other programming languages like Java, Ruby only has dynamic arrays but no static arrays. That means you don’t have to worry about the size of the array while adding new values.

There are multiple ways we can Initialize an empty array.

names = Array.new

# or

names = []

Fill an array with the initial size and a default object.

numbers = Array.new(3, 7)

# [7, 7, 7]

# or

numbers = [7, 7, 7]

# [7, 7, 7]

# or

numbers = []

numbers.fill(7, 0..2)

# [7, 7, 7]

How about an array with different hashes? No problem, Ruby has you covered!

array_with_hashes = Array.new(2) { {} }

# [{}, {}]

array_with_hashes[0][:name] = "Bob"

array_with_hashes[0][:id] = 10

# [{:name=>"Bob", :id=>10}, {}]

Let’s talk about 2D arrays briefly.

temperature_data = [

["A908", 38],

["A909", 37],

["A910", 38],

]

temperature_data[0]

# ["A908", 38]

temperature_data[0][0]

# "A908"

temperature_data[0][1]

# 38

Arrays are integer-indexed and start at 0. A negative index is used to access the array elements from the end, so -1 is the last element of the array, -2 is the second last element in the array, and so on.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

planets[0]

# "Mercury"

planets[-1]

# "Neptune"

We can use the keyword first and last to access the first and last element of an Array.

planets.first

# "Mercury"

numbers.last

# "Neptune"

How about a block to populate the values of an array?

numbers = Array.new(10) { |n| n = n * 2 }

# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

It gets easier to fill an array.

numbers = Array(100..110)

# [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]

# or we can convert a range to an array

(100..110).to_a

# [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]

Now let’s talk about adding elements to the array. We can add values at the end of the array by using the push method.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers.push(11)

# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

numbers.push(12, 13, 14)

# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Add values at the start of the array.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers.unshift(0)

# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers.unshift(-3, -2, -1)

# [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Insert values at the given index.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers.insert(0, 0)

# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers.insert(0, -3, -2, -1)

# [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] numbers.insert(-1, 12, 13, 14)

# [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14]

numbers.insert(-4, 11)

# [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Now that we have some elements in our arrays, I’m going to discuss some methods that will help us retrieve multiple values.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# numbers[start..end], both index are inclusive

puts numbers[0..3]

# 1

# 2

# 3

# 4 # numbers[start..end], end index is exclusive

puts numbers[0...3]

# 1

# 2

# 3 # or numbers[start..length]

puts numbers[0, 1]

# 1

There are two more methods that you should know, take and fetch .

# Get first n elements of an Array

primes = [7, 2, 3, 5]

primes.take(3)

# [7, 2, 3]

# The take method will not raise any error if it does not satisfy the condition

primes.take(10)

# [7, 2, 3, 5] # Access an element

primes.fetch(3)

# 5

# Fetch will throw an error if the element does not exist

primes.fetch(10)

(index 10 outside of array bounds: -4...4)

# or get an default value

primes.fetch(10, -1)

# -1

One last thing! You can either use size or length; both are synonymous.

names = Array.new(10)

puts names.size

# 10

puts names.length

# 10

The essentials

The method sample will return a random value from an array.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers.sample

# 2

numbers.sample(3)

# [9, 4, 2]

Clearing an array comes in handy from time to time.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers.clear

# output

# []

Merging two arrays has never been easier with the merge method.

a = ["tom", "mot", "otm"]

b = [2, 3, 5]



a.zip(b)



# outout

# [["tom", 2], ["mot", 3], ["otm", 5]]

Sorting is most probably one of the most used operations in computer science.

primes = [7, 2, 3, 5]

sorted_primes = primes.sort

puts "#{sorted_primes}"

# output

# [2, 3, 5, 7] # or in-place sort primes = [7, 2, 3, 5]

primes.sort!

puts "#{primes}"

# output

# [2, 3, 5, 7] planets.sort_by { |p| p.length }

# output

# ["Mars", "Earth", "Venus", "Saturn", "Uranus", "Neptune", "Jupiter", "Mercury"]

Remove duplicate elements from an array.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 1]

numbers.uniq

# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Check if a value exists in an Array or not.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

planets.include? "Mars"

# output

# true planets.include? "Pluto"

# output

# false

The must-haves

Sometimes we need to iterate an array to manipulate the data.

# when you have single line block

salary = [399, 234, 566, 533, 233]

salary.each { |s| puts s }

# output

# 399

# 234

# 566

# 533

# 233 # when you have a multi-line block, you can replace the curly brackets {} with do and end

salary.each do |s|

a = 10

res = a * s

puts res

end

# output

# 3990

# 2340

# 5660

# 5330

# 2330



# or you can do the same thing just using curly brackets {} and semicolons as separators instead of new lines

salary.each { |s| a = 10 ; res = a * s ; puts res }

If you care about the index.

salary = [399, 234, 566, 533, 233]

salary.each_with_index { |value, index| puts "#{index} #{value}" }

# output

# 0 399

# 1 234

# 2 566

# 3 533

# 4 233

There is another method called map , which returns an array containing the values returned by the block. On the other hand, each returns the original values.

salary = [399, 234, 566, 533, 233]

salary.map { |s| s * 10 }

# returns

# [3990, 2340, 5660, 5330, 2330]



# on the other hand each returns the original values

salary = [399, 234, 566, 533, 233]

salary.each { |s| s * 10 }

# returns

# [399, 234, 566, 533, 233]

When you want a single value. It’s helpful when you want to accumulate, concatenate. The reduce and inject methods are aliases.

numbers = [2, 2, 2, 2, 2]

numbers.reduce(11, :+)

# output

# 21

The detect method returns the first item if matched the condition, returns nil otherwise. It’s helpful when you are looking for something based on business logic. The find and detect methods are aliases.