6

This piece of code:

def func *; end
[func "hello"]

is parsed without error in Ruby 1.8.7, but returns a syntax error:

syntax error, unexpected ']', expecting '}'

in Ruby >= 1.9. I looked through What is the difference between Ruby 1.8 and Ruby 1.9, but couldn't find a reference to this. Does anyone know what change is causing this?

Community
  • 1
  • 1
Aman Gupta
  • 557
  • 1
  • 8
  • 23
  • 1
    just to see - could you try `r = [ func("hello")]` ? – Arup Rakshit Sep 10 '13 at 13:11
  • @Babai no. It is a syntax error: `syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('`. Seems to be a precedence issue, since calling the method with parenthesis works. – fotanus Sep 10 '13 at 13:35

1 Answers1

5

It's to avoid ambiguity. Consider the following:

def foo(a, b = 1) # foo takes an optional second argument
end

[foo 1, 2]

This could be interpreted as [(foo 1), 2] or as [(foo 1, 2)].

There are two references in the Calling Methods docs (although not directly related to the array literal):

Note that the parenthesis are optional ... Except when there is difference between using and omitting parentheses

In many cases parenthesis are not necessary when sending a message ... However, parenthesis are necessary to avoid ambiguity.

Community
  • 1
  • 1
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • def foo(a) end; [foo 1] generates the same error in v2.0.0, yet there is no ambiguity here. – Cary Swoveland Sep 10 '13 at 17:06
  • @CarySwoveland the error is raised at the parser level, regardless of the method definition. After all, Ruby is a dynamic language allowing you to change the method at any time. – Stefan Sep 10 '13 at 17:32
  • In my example, `def foo(a) end`, I noticed `[foo 1]` and `[foo (1)]` both produce errors, but `[foo(1)]` is OK. I know it is good practice to avoid spaces between a method name and the opening parenthesis, but they are permitted in some cases, though it seems a bit vague as to where they are permitted. In any event, I assume `[foo 1]` is treated as `[foo (1)]` in this regard, so maybe that's what the parser is looking at. – Cary Swoveland Sep 10 '13 at 18:12