Including and Excluding in Rails-6


Including and Excluding in Rails-6

Rails 6 has been very exciting since it has so many features, which we found quite helpful from development perspective.

Let’s have a few method that has been added worth looking at including and excluding.


Using #excluding in Rails 6

Previously this was provided as without for Enumerable#without or Array#without returns the array without the provided value as a parameter.

Example:

# In Rails 5
[1, 2, 3].without(2)
=> [1, 3]

[1, 2, 3].without([1, 3])
=> [2]

This method has actually been renamed from without to excluding keeping without as an alias to excluding. So, in rails-6 we will be able to use both of them.

Example:

# In Rails 6
[1, 2, 3].excluding(2)
  => [1, 3]

[1, 2, 3].excluding([1, 3])
  => [2]


Including

Rails-6 adds including method as a counter part to excluding or without method. including does what excluding does, in opposite manner. It includes the passed value as parameter along with the Array or Enumerable on which it was invoked.

Example:

[1, 2, 3].including(33)
=> [1, 2, 3, 33]

[1, 2, 3].including([22, 23])
=> [1, 2, 3, 22, 23]


# With duplicate values

[1, 2, 3].including([2, 3])
=> [1, 2, 3, 2, 3]

Recommended Posts

Default Enum in Rails 6
Rails 6 provides a way to define default enum value. Let’s see how it works...
Ruby 2.7 adds Enumerable#tally
After introducing the Enumerable#tally method in Ruby 2.7-preview updates. #tally as the name suggests gives...
How to rename column name in Rails
Rails rename_column Rails provides a simple method rename_column which can be used in a migration....