Is there any difference between
[1, "hi", []]
and
Array[1, "hi", []]
and
Array.[1, "hi", []]
If there is no difference (as ri 'Array::[]' suggests) why Array[...] and Array.[...] exist?
The last example would have to be written like:
Array.[](1, 'hi', [])
This last way of writing an array shows that Array::[] is just another method of the class Array. The method takes x splat arguments and creates/returns the new array.
The other ways of writing an array are just syntax sugar provided in Ruby for easy readability and convenience
Also, looking at the source code, we can see a new array is created and returned at the end:
static VALUE
rb_ary_s_create(int argc, VALUE *argv, VALUE klass)
{
VALUE ary = ary_new(klass, argc);
if (argc > 0 && argv) {
MEMCPY(RARRAY_PTR(ary), argv, VALUE, argc);
ARY_SET_LEN(ary, argc);
}
return ary;
}
Array::[]. Try overriding Array::[] and see what happens when you use the literal syntax. Hint: nothing changes.Yes, there is.
The first is an Array literal. Literals are built into the language specification, Ruby does not allow overriding, modifying, or otherwise changing or influencing the meaning of a literal.
The second is a method call. Ruby does allow modifying the behavior of methods, ergo, someone, somewhere could have changed the definition of Array::[] to do something different.
The third is a SyntaxError, so it is very obviously not equivalent to either of the other two.
Array.[](1, "hi", [])instead ofArray.[1, "hi", []]