Why do I need parentheses here?


#1

I have a function

def f(x)
...
end

which I can call like this:

y = f 5
y = f(5)

I can not use the form without parentheses to construct a one-element
array:

y = [f 5]

–> syntax error, unexpected tINTEGER, expecting keyword_do or ‘{’ or
‘(’

Obviously, Ruby can’t disambiguate between block argument and function
call, so I have to write

y = [f(5)]

Why does the context (array constructor) make a difference with respect
to disambiguation?


#2

Why does the context (array constructor) make a difference with
respect to disambiguation?

I don’t think the context per se plays the role, but instead of
what the parser is trying to do.

You can compare this if you create a new array without []:

def f(i)
  return i
end
Array.new(f 5) # => [nil, nil, nil, nil, nil]

This will work, so there is something inherently different for the use
of [].

I can’t off the top of my head name why [] is parsed differently but I
think there exists a reason why it is not possible, as otherwise it
would have been allowed by the lexer/parser or however it is called.