This blog is part of our Rails 6 series. Rails 6.0 was recently released.

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 the concatenation of the given collections.

# multiple arguments can be passed to including
>> [1, 2, 3].including(4, 5)
=> [1, 2, 3, 4, 5]

# another enumerable can also be passed to including
>> [1, 2, 3].including([4, 5])
=> [1, 2, 3, 4, 5]

>> %i(apple orange).including(:banana)
=> [:apple, :orange, :banana]

# return customers whose country_code is IN along with the prime customers
>> Customer.where(country_code: "IN").including(Customer.where(prime: true))

Array#excluding and Enumerable#excluding

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

# multiple arguments can be passed to including
>> [11, 22, 33, 44].excluding([22, 33])
=> [11, 44]

>> %i(ant bat cat).excluding(:bat)
=> [:ant, :cat]

# return all prime customers except those who haven't added their phone
>> Customer.where(prime: true).excluding(Customer.where(phone: nil))

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

>> [11, 22, 33, 44].without([22, 33])
=> [11, 44]

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

Check out the commit for more details on this.