1

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.

2
  • Dude, Eric. Didn't I teach you better? That code is desperately crying out for a ternary operator! :) Commented Oct 15, 2011 at 1:58
  • I originally (and may again) wrote it to also accept a proc in the condition position (one that takes the object as its parameter), which seemed cleanest as a 3-branch conditional. I use ternaries, I do! Commented Oct 17, 2011 at 13:30

1 Answer 1

5

This has nothing to do with any of your code — the and operator 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.

Sign up to request clarification or add additional context in comments.

4 Comments

I wonder how I've never run into that restriction before? Seems to be the only problem, thanks :-)
I found a thread at ruby-core about this topic. See matz comment and an answer on it.
@knut: Thanks for that. Got to love when your wild guesses are actually right.
I still haven't adapted to thinking of comma as an operator.. This makes sense now though; thanks for the discussion link!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.