DEV Community

Cover image for Most common Ruby array methods every dev should know
Erin Schaffer for Educative

Posted on • Originally published at educative.io

Most common Ruby array methods every dev should know

Arrays are objects that store other objects. You can think of an array as a bag that you can throw items in. The bag itself is an object, along with the other items you store inside the bag. Ruby arrays are a very popular data structure, and they can be used to store many different data types. Today, we’re going to take a look at some of the common Ruby array methods every dev should know.

We’ll cover:

What are array methods in Ruby?

Array methods in Ruby are essentially objects that can store other objects. You can store any kind of object in an array. You can create an array by separating values by commas and enclosing your list with square brackets.

In Ruby, arrays always keep their order unless you do something to change the order. They are zero-based, so the array index starts at 0.

There are many different things you can do with arrays such as:

  • Addition
  • Subtraction
  • Intersection
  • And much more

Before we dive into some fundamental Ruby array methods, let's take a look at two ways you can create a Ruby array.

1. The literal constructor

You can create a new array using the literal constructor:

array = [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

2. The new keyword

You can also create a new array using array.new. You can either create it as an empty array, create it with an initial size, or create it with two arguments (the initial size and the default object). The syntax is shown below:

array = Array.new 
#=> []

Array.new(4) 
#=> [nil, nil, nil, nil]

Array.new[4, false] 
#=> [false, false, false, false]
Enter fullscreen mode Exit fullscreen mode

Common array methods

There are a lot of array methods built into Ruby's array class. Let’s take a look at some of the most common methods.

.concat

The concat method appends elements from an array to the original array.

array = [1, 3, 5, 7]
array.concat([9, 11, 13])
#=> [1, 3, 5, 7, 9, 11, 13]
Enter fullscreen mode Exit fullscreen mode

.delete and .delete_at

The delete method deletes an element by name.

languages = ["Ruby", "Python", "Java"]
languages.delete("Python") 
#=> ["Ruby", "Java"]
Enter fullscreen mode Exit fullscreen mode

The delete_at method permanently deletes an element at a specified index.

languages.delete_at(1)
#=> ["Ruby", "Java"]
Enter fullscreen mode Exit fullscreen mode

Note: There is also .delete_if method, which conditionally deletes elements of an array.

.drop

The drop method returns the elements after n elements have been dropped.

array = [1, 2, 3, 4, 5, 6, 7, 8]
array.drop(3)
#=> [4, 5, 6, 7, 8]
Enter fullscreen mode Exit fullscreen mode

.each

The each method works on objects that allow for iteration. This method iterates through each element in the array.

cats = ["Waffle", "Coconut"]
cats.each {|cat| puts "Hi, #{cat}""}
#=> Hi, Waffle
#=> Hi, Coconut
Enter fullscreen mode Exit fullscreen mode

.empty?

The empty? method checks whether the array contains any elements.

colors = ["blue", "green", "red"]
colors.empty? 
#=> false
Enter fullscreen mode Exit fullscreen mode

.first and .last

The first method returns the first element of the array.

dogs = ["Daschund", "Poodle", "Pug"]
dogs.first 
#=> Dachshund
Enter fullscreen mode Exit fullscreen mode

The last method returns the last element of the array.

dogs = ["Daschund", "Poodle", "Pug"]
dogs.last 
#=> Pug
Enter fullscreen mode Exit fullscreen mode

.join

The join method returns a string of the elements of the array separated by a separator parameter.

array.join 
#=> "135"

array.join(“*”)
#=> "1*3*5"
Enter fullscreen mode Exit fullscreen mode

.length

To find your array length, you can use the length method. It will return the number of elements in the array.

friends = ["Foo", "Kathy", "Blake"]
friends.length 
#=> 3
Enter fullscreen mode Exit fullscreen mode

.map

The map method takes an operation and applies it to every element of an array, then returns the modified array.

array = [4, 6, 7]
array.map{ | number | number + 5 }
#=> [9, 11, 12]
Enter fullscreen mode Exit fullscreen mode

.push and .pop

The push method allows you to add an element to the end of the array.

array = ["seconds", "minutes"]
array.push("hours") 
#=> ["seconds", "minutes", "hours"]
Enter fullscreen mode Exit fullscreen mode

The pop method removes the last element of the array.

array = ["seconds", "minutes", "hours"]
array.pop 
#=> ["seconds", "minutes"]
Enter fullscreen mode Exit fullscreen mode

.reverse

The reverse method puts the array into reverse order. The original array remains the same.

Let’s say your original array looks like this:

arr = [1, 3, 5, 7, 9]
Enter fullscreen mode Exit fullscreen mode

When you implement the reverse method, it looks like this:

arr.reverse
#=> [9, 7, 5, 3, 1]
Enter fullscreen mode Exit fullscreen mode

.rindex

The rindex method returns the index of the last element which matches the parameter of rindex. It returns nil if no match is found.

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

array.rindex(7)
#=> nil
Enter fullscreen mode Exit fullscreen mode

.shift and .unshift

The shift method removes and returns the first element of the array.

jewelry = ["necklace", "ring", "earring"]
jewelry.shift
#=> ["ring", "earring"]
Enter fullscreen mode Exit fullscreen mode

The unshift method allows you to add an element to the beginning of an array.

jewelry = ["necklace", "ring", "earring"]
jewelry.unshift("bracelet") 
#=> ["bracelet", "necklace", "ring", "earring"]
Enter fullscreen mode Exit fullscreen mode

.sort

The sort method sorts the elements from least to greatest.

numbers = [10, 5, 25, 15]
numbers.sort
#=> [5, 10, 15, 25]
Enter fullscreen mode Exit fullscreen mode

.take

The take method returns the first n elements of the array.

array = [1, 2, 3, 4, 5, 6]
array.take(4)
#=> [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

.uniq

The uniq method takes an array with duplicate elements and returns a copy of the original array but with the duplicate values removed.

chocolates = ["Snickers", "Twix", "Twix", "Hershey", "KitKat"]
chocolates.uniq 
#=> ["Snickers", "Twix", "Hershey", "KitKat"]
Enter fullscreen mode Exit fullscreen mode

Advanced array concepts and next steps

Ruby arrays are an important data structure, and you can use them to store many different data types. Now that you've covered some common Ruby array methods, it's time to learn more about advanced array methods and concepts such as:

  • .with_index and .each_index

  • .flatten

  • Nested arrays

  • Multi-dimensional arrays

  • And much more

To continue learning more about Ruby, check out Educative’s course Learn Ruby from Scratch. This interactive course covers the fundamentals of the Ruby programming language. By the end of the course, you’ll be able to use Ruby with confidence and will have your own Ruby certificate to add to your resume.

Happy learning!

Continue reading about Ruby

Oldest comments (1)

Collapse
 
tax79 profile image
tax79

There is a typo

Array.new[4, false] 
Enter fullscreen mode Exit fullscreen mode

Should be

Array.new(4, false)
Enter fullscreen mode Exit fullscreen mode