Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does attr_accessor require using symbols as variables in Ruby?

Every example of attr_accessors I've seen uses a symbol (:var) as the variable.

Is this a requirement of using attr_accessorand, if so, why? If not, why is it such a common practice?

like image 233
zapatos Avatar asked Jan 19 '14 21:01

zapatos


People also ask

What does Attr_accessor mean in Ruby?

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 .

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 are symbols in Ruby?

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.

What does Attr_reader do in Ruby?

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.


2 Answers

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

like image 113
Arup Rakshit Avatar answered Sep 30 '22 14:09

Arup Rakshit


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.

like image 43
PinnyM Avatar answered Sep 30 '22 16:09

PinnyM