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.
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)
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, along with Enumerable#filter
, Enumerable#filter!
,
Enumerable#select!
was also added as an alias.
Here is the relevant commit and discussion.
If this blog was helpful, check out our full blog archive.