In Ruby there are four different getter and setter methods for instance variables, attr
, attr_reader
, attr_writer
, and attr_accessor
. The question is, is in Ruby attr :dilithium
, the same as attr_reader :dilithium
, and identical to attr_accessor :dilithium
if an additional parameter true is passed? That is to say is
class Enterprise attr :dilithium, true
identical to
class Enterprise attr_accessor :dilithium
Are the two functions attr
and attr_accessor
more or less redundant?
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.
Summary. attr_reader and attr_writer in Ruby allow us to access and modify instance variables using the . notation by creating getter and setter methods automatically. These methods allow us to access instance variables from outside the scope of the class definition.
What is attr_accessible? In Ruby on Rails, attr_accessible allows you to specify which attributes of a model can be altered via mass-assignment (most notably by update_attributes(attrs) and new(attrs) ). Any attribute names you pass as parameters will be alterable via mass-assignment, and all others won't be.
Attributes are key-value pairs containing information that determines the properties of an event or transaction.
One difference is that attr_accessor
and friends are clearer, and the optional boolean argument to attr
is now deprecated. Other than that, and the fact that attr
has no documentation, there's no real difference.
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