Rails 6 adds including & excluding method on Enumerables

Akhil Gautam

Akhil Gautam

August 18, 2020

This blog is part of our  Rails 6 series.

Rails 6 added including and excluding on Array and Enumerable.

Array#including and Enumerable#including

including can be used to extend a collection in a more object oriented way. It does not mutate the original collection but returns a new collection which is the concatenation of the given collections.

1
2# multiple arguments can be passed to including
3
4> > [1, 2, 3].including(4, 5)
5> > => [1, 2, 3, 4, 5]
6
7# another enumerable can also be passed to including
8
9> > [1, 2, 3].including([4, 5])
10> > => [1, 2, 3, 4, 5]
11
12> > %i(apple orange).including(:banana)
13> > => [:apple, :orange, :banana]
14
15# return customers whose country_code is IN along with the prime customers
16
17> > Customer.where(country_code: "IN").including(Customer.where(prime: true))
18

Array#excluding and Enumerable#excluding

It returns a copy of the enumerable excluding the given collection.

1
2# multiple arguments can be passed to including
3
4> > [11, 22, 33, 44].excluding([22, 33])
5> > => [11, 44]
6
7> > %i(ant bat cat).excluding(:bat)
8> > => [:ant, :cat]
9
10# return all prime customers except those who haven't added their phone
11
12> > Customer.where(prime: true).excluding(Customer.where(phone: nil))
13

Array#excluding and Enumerable#excluding replaces the already existing method without which in Rails 6 is now aliased to excluding.

1
2> > [11, 22, 33, 44].without([22, 33])
3> > => [11, 44]
4

excluding and including helps to shrink or extend a collection without using any operator.

Check out the commit for more details on this.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.