This blog is part of our Ruby 2.6 series. Ruby 2.6.0-preview2 was recently released.

Ruby 2.6 has added Enumerable#filter as an alias of Enumerable#select. The reason for adding Enumerable#filter as an alias is to make it easier for people coming from other languages to use Ruby. A lot of other languages including Java, R, PHP etc. have filter method to filter/select records based on a condition.

Let’s take an example in which we have to select/filter all numbers which are divisible by 5 from a range.

Ruby 2.5

irb> (1..100).select { |num| num % 5 == 0 }
=> [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

irb> (1..100).filter { |num| num % 5 == 0 }
=> Traceback (most recent call last):
2: from /Users/amit/.rvm/rubies/ruby-2.5.1/bin/irb:11:in `<main>' 1: from (irb):2 NoMethodError (undefined method`filter' for 1..100:Range)

Ruby 2.6.0-preview2

irb> (1..100).select { |num| num % 5 == 0 }
=> [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

irb> (1..100).filter { |num| num % 5 == 0 }
=> [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

Also note that along with Enumerable#filter, Enumerable#filter! is also added as an alias for Enumerable#select!.

Here is relevant commit and discussion.