Does Ruby's attr_accessor automatically create instance variables for attributes?
ruby
Solution
No. Instance variables are not defined until you assign to them, and `attr_accessor` doesn't do so automatically.
Attempting to access an undefined instance variable returns `nil`, but doesn't define that variable. They don't actually get defined until you write to them. `attr_accessor` relies on this behaviour and doesn't do anything except define a getter/setter.
You can verify this by checking out `.instance_variables`:
class Test
attr_accessor :something
end
A new instance of `x` has no instance variables:
x = Test.new # => #<Test:0xb775314c>
x.instance_variables # => []
Invoking the getter does not cause `@something` to become defined:
x.something # => nil
x.instance_variables # => []
Invoking the setter does cause `@something` to become defined:
x.something = 3 # => 3
x.instance_variables # => ["@something"]
Setting `something` back to `nil` doesn't cause `instance_variables` to revert, so we can be sure that the first empty array returned isn't simply a case of `instance_variables` omitting `nil` values:
x.something = nil # => nil
x.instance_variables # => ["@something"]
You can also verify that this isn't simply behaviour specific to `attr_accessor`:
class Test
def my_method
@x # nil
instance_variables # []
@x = 3
instance_variables # ["@x"]
end
end
Test.new.my_method
Problem
For example, if we write ``` class MyClass attr_accessor :something end ``` but did not explicitly create an initialize method with instance variable `@something`, does Ruby automatically create it?