Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top