Why is '[fx [1]]' not grammatical, but '[1 + x [1]]' is there?

For an array x, grammar expressions follow:

  • puts x[1]
  • [puts(x[1])]
  • [1 + x[1]]

but this:

  • [puts x[1]]

cannot parse:

syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('

Why can't the parser determine this syntax?

+4
source share
2 answers

I believe this parsing behavior is intentional and not an error. This is an unfortunate side effect of Ruby, allowing you to skip parentheses. This code is of course fine:

def f x, y=0
  x + y
end

f 2    # 2
f 2, 3 # 5

But what is the result of this code?

[f 2, 3]

[2,3] [5]? , , . Ruby , , .

, , , , , (- , ) .

: , , ,

[3, f 2]
# should be [3, 2]

, , , , . .

+8

Ruby , . , . Ruby , , , .

:

[puts(x[1])]

puts nil, .

+6

Source: https://habr.com/ru/post/1689270/


All Articles