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?
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.
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.
attr_accessor is used to define an attribute for object of Model which is not mapped with any column in database.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With