Ikbear
Ikbear

Reputation: 1307

What's wrong with this ruby code? syntax error, unexpected tIDENTIFIER, expecting keyword_end

This code comes from the book named Ruby Best Practice:

def respond_to?(message)
  message = message.to_sym
  [:__result__, :inspect].include?(message) ||
    __result__.respond_to? message
end

But I get an error: syntax error, unexpected tIDENTIFIER, expecting keyword_end. What's the matter?

Upvotes: 3

Views: 6468

Answers (1)

ecoologic
ecoologic

Reputation: 10420

You need some more parenthesis, like so

def respond_to?(message)
  message = message.to_sym
  [:__result__, :inspect].include?(message) ||
    __result__.respond_to?(message)
end

or (but looks uglier)

def respond_to?(message)
  message = message.to_sym
  [:__result__, :inspect].include?(message) ||
    (__result__.respond_to? message)
end

anyway what ruby understands is:

def respond_to?(message)
  message = message.to_sym
  ([:__result__, :inspect].include?(message) ||
    __result__.respond_to?) message
end

because of the operator priority.

I love to call functions without parenthesis, but this is a good thing only when the code is not ambiguous, ruby does not assign any priority to a new line as it does for the || function.

Upvotes: 4

Related Questions