Question

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

Was it helpful?

Solution

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,
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top