ActiveSupport – Array

In this blog post, I will write about some of the magical methods or tricks that ActiveSupport#Array provides us.

The first method which blew my mind was ‘in_groups_of’. This method is used to split the array in groups of a number. Ex:

%w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group}

The result would be:

["1", "2", "3"]
["4", "5", "6"]
["7", "8", "9"]
["10", nil, nil]

This is pretty straight forward. The cool part is we can pass a parameter to fill the empty places with. By default it is nil. For ex:

%w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3, 'my parameter') {|group| p group}

The result would be:

["1", "2", "3"]
["4", "5", "6"]
["7", "8", "9"]
["10", 'my parameter', 'my parameter']

And this is not it. It goes one step further. If we do this:

%w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3, false) {|group| p group}

The result would be:

["1", "2", "3"]
["4", "5", "6"]
["7", "8", "9"]

Surprised…!! It does not fill with any value (nil or false) when false is passed as the second parameter. This is pretty neat..!! You can read about it or if you want to see the source code for this method, read here( rails/active_support/lib/active_support/core_ext/array/grouping.rb)

Next up is ‘to_sentence’. to_sentence is used to convert the elements of an array to a sentence using word connectors. For ex:

['one', 'two'].to_sentence
# => "one and two"   

We can even pass the connector for the words. Ex:

['one', 'two'].to_sentence(two_words_connector: '-')
# => "one-two"
['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ')
# => "one or two or at least three"

And we can even pass which language to use for connections. ex:

['uno', 'dos'].to_sentence(locale: :es)

You can read more about it here, from the source code:

These are pretty neat methods which ActiveSupport provides us. There are more methods which I could have mentioned, but if you want to find out more such methods the best way is to read the rails source code.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s