Both cases are exactly equivalent because of the comma in line 2: the comma means that you are passing two arguments to attr_accessor
, not one.
What is the second argument? Well, it's what comes after the comma, of course, which is the def
expression. In older versions of Ruby, the return value of a method definition expression was implementation defined (in some implementations it returned nil
, in some the compiled bytecode of the method), but in current versions of Ruby, the return value of a def
expression is standardized to be a Symbol
denoting the name of the method being def
ined. So, in this case, the def
expression evaluates to :initialize
.
Now, because Ruby is a strict language, arguments are evaluated before they are passed, which means the def initialize
is evaluated first, which defines an initialize
method with one parameter.
However, immediately after that, attr_accessor
is called with two arguments, :username
and :initialize
, and as a result, attr_accessor
will create four methods: username=
, username
, initialize=
, and initialize
, thus overwriting the method we just defined with one that has no parameter.
That's why the two examples are the same: while the two initialize
methods are different initially, they immediately get overwritten with an identical method.
(I guess, technically, you could observe the difference, if you managed to call initialize
from a different thread at just the right time, directly after it is being defined the first time but before it is being overwritten. That's an extremely tiny window, though.)
Note that the code you posted will generate a warning to that effect:
user.rb:2: warning: method redefined; discarding old initialize
user.rb:3: warning: previous definition of initialize was here
You can see the effect of the strict evaluation of the arguments here in the line numbers: it complains that the method is being overwritten in line 2 but was previously defined on line 3, which actually comes after 2 but was evaluated before it.
This shows something I have written about over and over and over again: you should actually read the warnings. They were put in there for a reason.