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

有帮助吗?

解决方案

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,
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top