I Just started learning ruby and I don’t see the difference between an @instace_variable and an attribute declared using attr_accessor.
What is the difference between the following two classes:
class MyClass
@variable1
end
and
class MyClass
attr_accessor :variable1
end
I searched lot of tutorials online and everybody uses different notation, Does it have to do anything with the ruby version? I also searched few old threads in StackOverflow
What is attr_accessor in Ruby?
What's the Difference Between These Two Ruby Class Initialization Definitions?
But still I am not able to figure out what is the best way to use.
An instance variable is not visible outside the object it is in; but when you create an
attr_accessor, it creates an instance variable and also makes it visible (and editable) outside the object.Example with instance variable (not
attr_accessor)Example using
attr_accessor:Hope that makes it clear.