So, thinking I’m all clever, I add a method like this to Object:
class Object
def apply_if(cond)
if cond
yield self
else
return self
end
end
end
This (I thought) allows my to conditionally add bits to a method chain, which simplifies my ActiveRecord query manipulation quite a bit. But it gives a syntax error, which I can reduce down to the following code:
data = [1,2,3,4,5]
results = data.
apply_if(true and false) do |q|
q + [0,0]
end
Likewise this errors:
results = data.apply_if(true and false){|q| q + [0,0]}
But this works:
results = data.apply_if ((true and false)) {|q| q + [0,0]}
As does:
results = data.apply_if (true && false) {|q| q + [0,0]}
I see that the differences there are all to do with operator precendence, but how can the precedence of an operator inside a pair of parentheses matter?
Why is there a syntax error here at all? I don’t see any likely syntactic ambiguities, and this method is identical in shape to the Array#reduce method.
I’ve tried a number of combinations here – explicit block parameters with calls, various types of explicit precedence inside the method definition. Using a lambda instead of a block worked fine, but is obviously too clunky to use for my purposes.
This has nothing to do with any of your code — the
andoperator just isn’t allowed in an argument list. As for why, you’d have to ask the Core team, but the most obvious possibility IMO is that its raison d’etre (having extremely low precedence) doesn’t work in an argument list.