Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attr_accessor vs attr_reader & instance variables

Tags:

ruby

could anyone please tell me the difference (if there are any) between

class Car
  attr_accessor :engine
  def initialize(engine)
    self.engine = engine
  end
end

and

class Car
  attr_reader :engine
  def initialize(engine)
    @engine = engine
  end
end

Or are they practically the same?

like image 566
lemon Avatar asked Nov 16 '13 13:11

lemon


People also ask

What is Attr_reader?

We use this when we need a variable that should only be changed from private methods, but whose value still needs to be available publicly. The attr_reader method takes the names of the object's attributes as arguments and automatically creates getter methods for each.

What is Attr_accessor?

attr_accessor is a shortcut method when you need both attr_reader and attr_writer . Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.

What is the use of Attr_accessor in rails?

attr_accessor is used to define an attribute for object of Model which is not mapped with any column in database.

What is Attr_accessible?

attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.


1 Answers

attr_accessor defines getter and setter.attr_reader defines only getter.

class Car
  attr_reader :engine
  def initialize(engine)
    @engine = engine
  end
end

Car.instance_methods(false) # => [:engine]

With the above code you defined only def engine; @engine ;end.

class Car
  attr_accessor :engine
  def initialize(engine)
    self.engine = engine
  end
end

Car.instance_methods(false) # => [:engine, :engine=]

With the above code you defined only def engine; @engine ;end and def engine=(engine) ;@engine = engine ;end.

like image 149
Arup Rakshit Avatar answered Sep 28 '22 10:09

Arup Rakshit