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:
If we want 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:
.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
.push
This method adds one or more elements to the end of any Array and returns a modified array. For example:
.at
This method takes in an Integer argument and returns the element in the specified index of an Array.
.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:
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!
Top comments (0)