0

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?

1
  • I made mistake in the third example Array.[](1, "hi", []) instead of Array.[1, "hi", []] Commented Jan 20, 2016 at 15:17

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. For some reason I thought that there must be some difference.
Array literals are not syntactic sugar for Array::[]. Try overriding Array::[] and see what happens when you use the literal syntax. Hint: nothing changes.
0

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.

1 Comment

Thank you. I made mistake in the third example.

Your Answer

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.