문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top