BigBinary Blog

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

Ruby 2.5 enumerable predicates accept pattern argument

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"

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"
5# Translates to:
7queries.any? { |sql| /LEFT OUTER JOIN/i === sql }

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.

Prathamesh Sonpatki in Ruby 2.5
January 2, 2018

Subscribe to our newsletter