2
def foo
  1,2
end

causes syntax error "unexpected ',', expecting keyword_end"

I'd think this is valid Ruby. What's wrong?

3
  • 1
    "I'd think this is valid Ruby. What's wrong?" – It's not. Commented May 28, 2015 at 18:42
  • @JörgWMittag that's quite obvious! I'm looking for reasoning. return 1,2 works. Going by Ruby convention of omitting return, I'd think just 1,2 would work. Commented May 28, 2015 at 18:54
  • 1
    @slowpoison there is a specific rules in Ruby's syntax for return followed by a comma separated list to return an array. Similarly if you have an assignment with a single variable on the left hand side (or a * variable) then this can assign an array too e.g. x = 1, 2. But there isn't a general syntax to make an array without the square brackets. Commented May 28, 2015 at 21:20

2 Answers 2

6

You're not returning an array.

You should have this:

def foo
  [1, 2]
end

Ruby isn't expecting a comma (,) because it isn't valid syntax. Integers in a simple array should be surrounded by brackets as well as delineated by a comma.

Sign up to request clarification or add additional context in comments.

Comments

5

If you used explicit return it will work.

def foo
  return 1,2
end

But that wouldn't work with implicit return. To make it work with implicit return you need to give it [1, 2].

2 Comments

I mentioned "without 'return'", so I knew that return works. I'm wondering why the difference.
@slowpoison That's how parser is written by Matz. :) I don't know the history behind this too, as I really never needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.