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.
if queries.any? { |sql| /LEFT OUTER JOIN/i =~ sql }
logger.log "Left outer join detected"
end
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.
if queries.any?(/LEFT OUTER JOIN/i)
logger.log "Left outer join detected"
end
# Translates to:
queries.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.
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.
If this blog was helpful, check out our full blog archive.