Ruby Array Methods

onetayjones

Taylor D Jones

Posted on February 22, 2024

Ruby Array Methods

Let's talk about Ruby's array methods... but first, what is an array?

Arrays are dynamic collections of elements, capable of storing any data type and adjusting in size as needed. With built-in methods for sorting, iteration, and transformation, arrays in Ruby offer flexibility and efficiency for managing collections of data.

Here are some methods demonstrating some of Ruby array's versatility:

.sample
This method returns a random element (or elements) from the array. Here are some examples:

.sample code sample

If we want multiple elements:

.sample code sample with multiple elements

.sort
This method returns a new array with the elements of the original array but it sorts the elements of the array in ascending order. Let's see this method in action:

.sort code sample

.count
Ruby's .count returns the number of elements in the array that meet certain conditions. It also returns the number of elements in a list, when given no arguments. If given an argument, returns the number of times that argument occurs in the array. In these instances, this method returns an Integer

simple .count code sample

complex .count code sample

.push
This method adds one or more elements to the end of any Array and returns a modified array. For example:

.push code sample

.at
This method takes in an Integer argument and returns the element in the specified index of an Array.

.at code sample

.join
You can think of this method as the inverse of String's .split method. It combines the elements of the array into a single string, separated by a specified delimiter. Here are some examples of using these different delimiters:

.join code samples

Of course, there are other array methods such as .sum, .min & .max, and .include. I hope these have been helpful for your Ruby learning journey.

Until next time, Happy Coding!

💖 💪 🙅 🚩
onetayjones
Taylor D Jones

Posted on February 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Ruby Array Methods
beginners Ruby Array Methods

February 22, 2024

Methods in Ruby
beginners Methods in Ruby

August 21, 2023

Hashes in Ruby
beginners Hashes in Ruby

August 20, 2023

Introdução ao Ruby
beginners Introdução ao Ruby

August 16, 2023