Difference between @instance_variable and attr_accessor

ruby

Solution

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`)

class MyClass
  def initialize
    @greeting = "hello"
  end
end

m = MyClass.new
m.greeting #results in the following error:
  #NoMethodError: undefined method `greeting' for #<MyClass:0x007f9e5109c058 @greeting="hello">

Example using `attr_accessor`:

class MyClass
  attr_accessor :greeting

  def initialize
    @greeting = "hello"
  end
end

m2 = MyClass.new
m2.greeting = "bonjour" # <-- set the @greeting variable from outside the object
m2.greeting #=> "bonjour"   <-- didn't blow up as attr_accessor makes the variable accessible from outside the object

Hope that makes it clear.

Problem

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.

Original source

Related problems