Ruby class with array attribute -


i have non-database-backed class in ruby:

class user   attr_accessor :countries end 

i want countries array of iso country codes (us, gb, ca, au, etc) , don't want build separate model hold each. there magic way make ruby understand :countries array , treat accordingly, or need write countries , countries= methods?

i tried setting countries array user.countries = ['us'], , i'm getting nomethoderror.

the type of variable doesn't matter in ruby.

attr_accessor creates getter , setter methods set , return instance variables; @countries in case. can set instance variable array, or use setter:

class user   attr_accessor :countries    def initialize     @countries = %w[foo bar baz]     # or...     self.countries = %w[foo bar baz]   end end  > puts user.new.countries => ["foo", "bar", "baz"] 

personally prefer using instance variable instead of self.xxx; it's easy forget self. bit , end setting local variable, leaving instance variable nil. think it's ugly.

if countries won't changing between instances, why not constant?

edit/clarification

tadman's point well-taken, e.g., this diatribe on state. circumtances under don't care limited small, self-controlled, stand-alone classes. there inherent risks in making assumptions, level of risks project-dependent.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

c++ - Clear the memory after returning a vector in a function -

erlang - Saving a digraph to mnesia is hindered because of its side-effects -