18 Apr

Array Tricks - Rails Tricks Issue 3


Hi, this is your weekly Rails Trick!


This time, I am bringing a few Active Support extensions on Array.


The first one is the to_sentence conversion method. By default, it converts the array to a comma-separated list of words, with the last element joined by “and”. For example:

a3589f39-0ec6-476e-82fe-d93d696e6d98.png 19.8 KB

You can specify the words_connector and the last_word_connector if you want to use something other than the comma and “and”:

d4371ed1-cbb5-435b-bf99-d5e373b694bc.png 48.5 KB

The next extension I want to mention is the ArrayInquirer. By calling inquiry on an array, you can convert it to an ActiveSupport::ArrayInquirer object. This will give you predicate methods on the string-like contents of the array. For example:

fb54923c-a11b-482f-b80a-d943f88717af.png 73.5 KB As a side note, Rails uses this internally for the variant predicates in Action Dispatch.

Active Support
also adds a few extra access methods to Array. There is from, which takes a position and returns the tail of the array from that position. There is to, which does the opposite and returns the beginning of the array up until the given position.


There is also the including method, which returns a new array including the elements passed to it. and you can achieve the opposite with excluding, which returns a new array excluding the elements passed to the method. excluding is actually implemented on Enumerable in Ruby, but Active Support reimplements it on Array to make it more performant. It is also worth mentioning that excluding is aliased as without.


There are also methods to access, second, third, fourth and the fifth elements of an array. And there is fourty_two, which has an interesting history. Back in the day, we had these helpers up till 10 (if my memory serves me well), and some people were complaining about them, saying they are bloating Active Support. As a response to the criticism, fourty_two was added as a kind of joke to access “the reddit”, implicating that it holds the Ultimate Answer to Life, the Universe, and Everything .


That’s it for this week!