Ruby 2.6 adds Enumerable#filter as alias of Enumerable#select

Amit Choudhary

By Amit Choudhary

on August 28, 2018

This blog is part of our  Ruby 2.6 series.

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 a 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

1irb> (1..100).select { |num| num % 5 == 0 }
2=> [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
3
4irb> (1..100).filter { |num| num % 5 == 0 }
5=> Traceback (most recent call last):
62: 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

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

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

Here is the relevant commit and discussion.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.