As @theTinMan alluded to in the comments, you must understand the distinction between the language (syntax) and the logic (semantics). For example, suppose someone asked you to write a program that prints the number 1,000. You'd probably write it like this:
puts 1000
But you could also write any of these:
puts 1_000
puts 0b1111101000
puts 01750
These are all the same. Not "the same" as in they produce the same results, but "the same" as in Ruby parses and executes them exactly the same way. Their syntaxes are different but their semantics are identical.
The same is true for Ruby's different array syntaxes (and for its equivalent string syntaxes, Regexp literals, etc.). You can test this yourself using Ruby's --dump insns
(dump instruction sequence) option:
$ ruby --dump insns -e 'arr = ["a", "b"]'
== disasm: <RubyVM::InstructionSequence:<main>@-e>======================
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 2] arr
0000 trace 1 ( 1)
0002 putstring "a"
0004 putstring "b"
0006 newarray 2
0008 dup
0009 setlocal_OP__WC__0 2
0011 leave
$ ruby --dump insns -e 'arr = %w(a b)'
== disasm: <RubyVM::InstructionSequence:<main>@-e>======================
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 2] arr
0000 trace 1 ( 1)
0002 putstring "a"
0004 putstring "b"
0006 newarray 2
0008 dup
0009 setlocal_OP__WC__0 2
0011 leave
Completely identical. The salient instructions, of course, are 0002–0006:
0002 putstring "a"
0004 putstring "b"
0006 newarray 2
These instructions say (more or less):
- (0002) Push the string
"a"
onto the top of the stack.
- (0004) Push the string
"b"
onto the top of the stack.
- (0006) Pop the top two values from the stack, make an array from them and push it onto the stack.
These are the actual instructions that the MRI VM will execute in both cases. Ruby never knows that you used %w( ... )
instead of [ ... ]
and there's no additional code it has to execute.