Forum: Ruby Why do I need parentheses here?

0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2016-07-19 06:50
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?
4828d528e2e46f7c8160c336eb332836?d=identicon&s=25 Robert Heiler (shevegen)
on 2016-09-04 02:19
> 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.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.