new user20
new user20

Reputation: 59

Regarding attr_accessor and def initialize

I want to add school names to array using attr_accessor.

My question is what 'def initialize()' is doing in this case

so that I can store data by using

v1.school_name[0] = "myschoolname"

If I omit the initialize() function I get the error

class StoreData

   attr_accessor :school_name
   def initialize
      @school_name = []
   end
end


v1 = Store_data.new 
v1.school_name[0] = "myschoolname"
print v1.school_name[0] 
v1.school_name[1] = "myschoolnamehighschool"
print v1.school_name

Upvotes: 1

Views: 749

Answers (2)

Thorin
Thorin

Reputation: 2034

attr_accessor is just an attribute and by default it is nil. You cannot assign any value to it. If you need it to an array then initialize it as an array before using it.

Upvotes: 2

tadman
tadman

Reputation: 211560

In this case you're initializing the @school_name with an empty array. If you don't do that it doesn't automatically create it, but it could. That pattern's called lazy initialization:

class StoreData
  def school_name
    @school_name ||= [ ]
  end
end

s = StoreData.new
s.school_name << "Name 1"
s.school_name << "Name 2"
s.school_name
#=> [ "Name 1", "Name 2" ]

You can't assign something to a nil value which is what instance variables are by default.

This one creates an array if necessary using the ||= operator.

Upvotes: 3

Related Questions