Inject double ampersand operator

ruby

Solution

You can't because `&&` and `||`, unlike other operators, are not syntacic sugar for methods (i.e. there is no method called `&&` or `||`), so you can't reference them using a symbol.

However you can avoid using `inject` to compute the logical conjunction or disjunction of an array of boolean values, replacing it with `all?` or `any?` respectively, because for any array the following conditions hold:

ary.inject(true) { |res, b| res && b } == ary.all?
ary.inject(false) { |res, b| res || b } == ary.any?

So, for example, the code you posted could be rewritten as:

[2,4,6].map(&:even?).all?
# => true

Update: obviously my latter example is not the right way to express this computation, falsetru's answer is much faster:

require 'fruity'

compare(
  -> { (0..1000).map(&:even?).all? },
  -> { (0..1000).all?(&:even?) }
)
Running each test 1024 times. Test will take about 2 seconds.
Code 2 is faster than Code 1 by 111x ± 10.0   

Problem

I have an inject call ``` [2,4,6].inject(true) { |res, val| res && val % 2 == 0 } ``` and want to send the `&&` operator to inject as in `inject(0, :+)`. How can I do that?

Original source