The documentation for attr_accessor
explicitly says that it creates an instance variable:
[...] creating an instance variable (
@name
) and a corresponding access method [...]
As does the documentation for attr_reader
:
Creates instance variables and corresponding methods [...]
I understand the second part, i.e. that attr_accessor
and attr_reader
create methods, but I don't get the first part.
What does it mean that they "create an instance variable"?
That's a bug/misleading wording in documentation. The attr_reader
/attr_accessor
themselves don't create any variables. How can they? They work outside of class instance lifecycle. And even read access don't make the instance variables come to life. Only write access creates them.
class Foo
attr_accessor :bar
end
foo = Foo.new
foo.instance_variables # => []
foo.bar # try read ivar
foo.instance_variables # => [], nope, not yet
foo.bar = 2 # write ivar
foo.instance_variables # => [:@bar], there it is