Every example of attr_accessor
s I've seen uses a symbol (:var
) as the variable.
Is this a requirement of using attr_accessor
and, if so, why? If not, why is it such a common practice?
Nouman Abbasi. In Ruby, object methods are public by default, while data is private. To access and modify data, we use the attr_reader and attr_writer . attr_accessor is a shortcut method when you need both attr_reader and attr_writer .
attr_accessor is used to define an attribute for object of Model which is not mapped with any column in database.
Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.
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.
Module#attr_accessor
attr_accessor(symbol, ...) → nil
attr_accessor(string, ...) → nil (newly introduced in Ruby 2.1)
Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. Also creates a method called name= to set the attribute. String arguments are converted to symbols.
Is this a requirement of using attr_accessor?
No, you are allowed with symbols as well as strings.
Read this - Understanding Ruby symbol as method call
While the current version of ruby (2.1) permits passing a string (as mentioned by @ArupRakshit), older versions of ruby did not (2.0 and prior). As such, any code that isn't relying on ruby 2.1 (and that would be almost everything) will need to pass symbols.
Aside for this, in most cases you'd want to be passing symbols anyhow, as they are atomic, have less overhead, and are semantically more in line with attribute definition than strings are.
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