Up Your Ruby Array Game With These Handy Methods
Array methods can save time and keep code looking neat and concise. Each programming language handles them a bit differently with Ruby having some of the more intuitive methods. Let’s take a look at some of them.
all? and any?
These two methods are useful for checking if contents of an array meet a certain criteria. Without a block they will check if the elements are truthy or falsey. Providing a block checks if any or all of the elements match the criteria within the block. The return values for these methods are true
or false
.
compact
Returns a new array that only contains elements that are not nil
. Saves time and improves readability over using filter
. I find this method useful in Rails for making sure only valid data gets passed off to the view. Seeing nil
on the page is not a good look.
intersection
Sometimes you may be dealing with multiple arrays and you want to find the common values between them. Introduced in Ruby 2.7, intersection
can be called on an array with each argument being an array to compare. It will return a new array containing the elements common between all the arrays . The order from the original array is retained without duplicates.
sample
This method will return a random element from an array. If you are anything like me and have been using rand()
and calling the index to draw an item randomly then this method will prove useful. Calling the method without an argument will return a single random element from the array. If an argument (n)
is provided then it will return an array with n
random elements. If the value of the argument is larger than the length of the array the amount of elements returned will match the length.
union
Say you want to combine 3 arrays into one. Some of the values in the arrays are the same so after merging them you have duplicates that you want to filter out. This can be achieved by using concat
to make one array and then calling uniq
on it to return an array without the duplicates. This works but why call two methods when the job can be done with just one? Meet the union
method.
These methods had flown under the radar for me and I recently discovered them during interview prep. Don’t let them evade you too as they save time and increase readability. Use them in your next Rails project, data structures and algorithms interview question, or coding challenge.