A few lesser-known but useful Ruby (on Rails) methods: Array

I’ve been a Ruby on Rails developer for 4.5 years. Naturally, in the beginning I tended to re-invent the wheel and write methods that I later found out were a part of the rich Ruby (on Rails) API. I think it’s important to have a good knowledge of the methods that exist. That way we code faster and our code is shorter, elegant and expressive.
One of the ways I discovered those methods is by solving code kata on HackerRank, Codewars or Exercism. I saw other people’s responses and realised that with Ruby, there is always a more elegant way.
So, I decided to write a series of articles covering lesser-known and practical Ruby (on Rails) methods. I will not copy the full documentation, but mention the method’s main usage and purpose with some examples. As I’m a foodie, the examples are from the domain of food, so careful: this article might make you hungry! 
In this first article I’ll cover the Array class.


Deletes every element of self for which the block evaluates to true. Exists also for Hash. There is also an “inverse” method,keep_if.

%w(chia flax pumpkin).delete_if { |s| s.length > 4 } 
# will delete 'pumpkin' and return ['chia', 'flax']

fetch(index, default)

This method is more often used on hashes, but on arrays it has the same behaviour. It returns the array’s element at the given index or the the specified default value. It also accepts a block to which the index is yielded if it doesn’t exist in the array.

%w(croissant Kouign-amann).fetch(1) # returns my favourite French pastry, 'Kouign-amann'
%w(croissant Kouign-amann).fetch(5, 'pain au chocolat') # returns 'pain au chocolat'
%w(croissant Kouign-amann).fetch(5) { |i| "There's no pastry at index #{i}." } # returns the fallback message


Turns an array of two-element arrays into a hash; interprets it as an array of [key, value] pairs.

[[:dish_type, 'salad'], [:main_ingredient, 'quinoa'], [:calories, 350]].to_h
# returns { dish_type: 'salad', main_ingredient: 'quinoa', calories: 350 }


Deletes all elements. Exists for Hash too.

sweets_shelf = ['granola bars', 'energy balls', 'dark chocolate']
sweets_shelf.clear # sweets_shelf is now empty


Cycles throught the array’s elements and yields each to the provided block. It does so the specified number of times or forever.

%w(croissant coffee).cycle(3) { |c| print c, ' ' }
# prints out 'croissant coffee croissant coffee croissant coffee'


Rotates the array so that the element at the index position becomes the first element.

%w(oats milk honey apricots).rotate(-3)
# returns ['milk', 'honey', 'apricots', 'oats'], the ingredients for a breakfast porridge
Porridge by minimalistbaker.com

sample(count = 1)

Returns n random elements from the array.

%w(chocolate figs hazelnuts).sample
# returns any of the 3 elements


[Rails] Class method. Wraps its arguments in an array unless it is already an array (or array-like).

Array.wrap 'crêpe' 
# returns ['crêpe']
French buckwheat crêpe from Breizh Café in Paris


[Rails] Creates a comma-separated sentence from the array’s elements. The last two elements are joined by the connector word (which is customisable and localisable).

['mozzarella', 'tomato', 'basil', 'olive oil', 'salt'].to_sentence
# returns 'mozzarella, tomato, basil, olive oil and salt', a simple recipe for caprese salad
Caprese salad. Image from one of my favourite food blogs, https://www.loveandlemons.com


[Rails] Returns the array without the specified elements.

%w(burger salad smoothie coke).without('burger', 'coke')
# returns healthy food options: ['salad', 'smoothie']

So, those were my favourite lesser-known Array methods.

What do you think? Do you use any? Or, maybe you have more to recommend? I would love to hear!