0

Why does this work? (at least on Ruby 2.0)

a = [1,2,]

If I add one more comma I get a syntax error.

Thanks

asked Oct 11, 2013 at 19:42
0

1 Answer 1

3

When defining an array, Ruby allows (but does not require) the last element to have a trailing comma:

a = [1, 2,]

This is especially handy when the array definition is on multiple lines:

a = [
 1,
 2,
]

With each element on its own line, and each element having a trailing comma, editing the list is trivial: it may be added to, deleted from, reordered, etc., without worrying about the trailing commas, and without having to touch any lines other than the ones you are editing. For example, if you add a new element, you don't have to add a comma to the preceding element.

Two commas in a row are not allowed.

Hashes allow the same convenience:

h = {
 :a => 1,
 :b => 2,
}
answered Oct 11, 2013 at 19:47
Sign up to request clarification or add additional context in comments.

2 Comments

In fact, this is the recommended way to write array/hash in multiple lines.
You can also do this when passing arguments to a method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.