Array Tricks - Rails Tricks Issue 3
Hi, this is your weekly Rails Trick!
This time, I am bringing a few Active Support extensions on
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”.
irb(main):001:0> [1, 2, 3].to_sentence => "1, 2, and 3"
You can specify the
words_connector and the
last_word_connector if you want to use something other than the comma and “and”:
irb(main):002:0> [1, 2, 3].to_sentence(words_connector: ' and ', last_word_connector: ' or ') => "1 and 2 or 3"
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.
irb(main):015:0> variant = [:phone, :tablet].inquiry irb(main):016:0> variant.phone? => true irb(main):018:0> variant.desktop? => false
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
from, which takes a position and returns the tail of the array from that posotion.
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. 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
There are also methods to access,
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 until 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!
Did you enjoy reading this? Sign up to the Rails Tricks newsletter for more content like this!
Or follow me on Twitter
I run an indie startup providing vulnerability scanning for your Ruby on Rails app.It is free to use at the moment, and I am grateful for any feedback about it.
If you would like to give it a spin, you can do it here: Vulnerability Scanning for your Ruby on Rails app!