Can anyone explain this array declaration to me?

℡╲_俬逩灬. 提交于 2019-12-01 17:49:22

问题


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


回答1:


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).




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/1791110/can-anyone-explain-this-array-declaration-to-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!