Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code work in ruby 1.8 and not ruby 1.9?

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?

like image 327
Aman Gupta Avatar asked Sep 10 '13 13:09

Aman Gupta


1 Answers

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.

like image 85
Stefan Avatar answered Oct 20 '22 15:10

Stefan