7

just wondering the difference between the presence of the last comma in the array, if there is any at all

>> [1,2,3]
=> [1, 2, 3]
>> [1,2,3,]
=> [1, 2, 3]

The second array still works, no exception raised

Thanks

John Topley
116k48 gold badges200 silver badges241 bronze badges
asked Nov 24, 2009 at 16:14
2
  • I suggest that you edit the question title into something a bit more explanatory. Commented Nov 24, 2009 at 16:15
  • I cleaned it up for him a little Commented Nov 24, 2009 at 16:17

3 Answers 3

12

There's no difference. In Ruby, you're free to add a trailing comma to an array. It makes syntax like this:

a = [
 1,
 2,
 3,
]

A bit nicer, in some cases (e.g., if you want to add an element, you simply add a 4, line and don't have to worry about checking for a comma on the last line).

answered Nov 24, 2009 at 16:17
Sign up to request clarification or add additional context in comments.

3 Comments

it doesn't add null or anything? Array length is the same w/ or w/o the comma?
No, no null value is added -- the array just contains the elements 1,2,3 in either case.
I guess there is no difference really eh? It really is just out of curiosity, I was coding and found something like this so I guess I would ask all you smart folks here.
0

It isn't a error, just a empty value(ignored by the compiler), but I suggest you to read Understanding Ruby Arrays

answered Nov 24, 2009 at 16:18

1 Comment

Where exactly does that link mention optional trailing comma?
-1

There is nothing special about arrays.

[1,2,3]

is the same as

Array.[](1,2,3)

so the values are just method call parameters. The same applies to

{a: 1, b: 2}

which is the same as

Hash.[](:a, 1, :b, 2)

And the reason trailing commas are allowed in method-call parameters is just because Ruby is designed like that, for the reasons of convenience that @mipadi mentioned.

answered Oct 11, 2013 at 19:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.