Ruby 2.5 enumerable predicates accept pattern argument

Prathamesh Sonpatki

By Prathamesh Sonpatki

on January 2, 2018

This blog is part of our  Ruby 2.5 series.

Ruby 2.5.0 was recently released.

Ruby has sequence predicates such as all?, none?, one? and any? which take a block and evaluate that by passing every element of the sequence to it.

1if queries.any? { |sql| /LEFT OUTER JOIN/i =~ sql }
2logger.log "Left outer join detected"
3end

Ruby 2.5 allows using a shorthand for this by passing a pattern argument. Internally case equality operator(===) is used against every element of the sequence and the pattern argument.

1if queries.any?(/LEFT OUTER JOIN/i)
2logger.log "Left outer join detected"
3end
4
5# Translates to:
6
7queries.any? { |sql| /LEFT OUTER JOIN/i === sql }
8

This allows us to write concise and shorthand expressions where block is only used for comparisons. This feature is applicable to all?, none?, one? and any? methods.

Similarities with Enumerable#grep

This feature is based on how Enumerable#grep works. grep returns an array of every element in the sequence for which the case equality operator(===) returns true by applying the pattern. In this case, the all? and friends return true or false.

There is a proposal to add it for select and reject as well.

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.