Ruby Arrays For Beginners: three useful array methods

Ifeoluwa Akinremi Wade
3 min readSep 11, 2021
Photo by Joshua Fuller on Unsplash

What are Ruby arrays, anyway?
Ruby arrays are basically lists of strings, integers, hash, or even other arrays. These items you find in arrays are called objects, or elements. The elements would also be enclosed inside two square brackets ([ ]). Arrays can be manipulated with array methods, which allow us to create, delete, inspect, or change elements in an array. This following blog will delve into three useful array methods.

is_a?

is_a? is an array method you would use to retain certain elements of a specific data type within an array. ie:

If I wanted to retain only the integers (whole number) of an array, I would utilize is_a? in this way:

In the image above, I am declaring a variable called numbers and initializing it with an array of elements consisting of strings and integers. I’m iterating through that array with the method keep_if (which I will discuss later in the blog). What this code is stating is: “Go through every element (num) in the numbers array and keep that element if the element is an Integer”. What will be returned is an array of elements that are of the Integer data type. The reverse result would happen if I was to inquire to keep an element if it is a String (characters enclosed with quotes, “ ”). What would then be returned is an array of strings.

is_a? can also be used as a boolean expression, an expression that evaluates to either true or false:

The above reads as: “23 Is a Float (decimal)”. Which then returns false because 23 is an Integer, a whole number.

delete_if

delete_if, to simply put it, deletes an element based on a condition. It is literally the opposite of keep_if.
ie:

Above I am declaring the variable thirties_club, and initialized it with an array of Integers. The code is stating: “delete any element if that element is less than 30”. What is returned is an array of integers that are 30 and above.

Just for fun though! How would I write this if 40 was in the same array?

it now states: “delete any element if that element is less than 30 or (||) greater than 39

or:

it can also be written like this: “delete any element if that element is less than 30 or (||) equal (===) to 40

keep_if

Unlike delete_if, keep_if retains — or keeps, an element based on a condition. If I was to use the same code used above, but instead used keep_if, the result would be as follows:

Aboves reads: “keep any element if that element is less than 30 or (||) equal (===) to 40. What is returned is an array that contains integers that are either less than 30 or equal to 40.

In my opinion, arrays are the most fun part of Ruby. Learning all of the array methods available only increases the fun by a thousand.

--

--