← Back to Upcase

Different ways of initializing variables in the initialize method


(Jon Seidel) #1

I’ve seen two different ways of setting up instance variables in the initialize method:

def initialize(names)
  self.games = games
end

and

def initialize(games)
  @games = games
end

Both could be accompanied by a

attr_accessor :games

With the both definitions, I could do:

results = Game.new( %w{game1 game2 game3}).games

and resutls would equal the list of three games. Inside the first Game class I can then reference that as ‘games’. while with the second Game class, I would use @games inside the class.

Is the name the only difference or is there something else going on that I can’t see?


(Derek Prior) #2

That method is calling the games= method. It’s not even necessarily setting an attribute. It may be doing so inside the method, or it may not. You may use the setter if you need to do some massaging of the data before the instance variable is set, for instance. Prefixing the setter with self. is required here because without it ruby has no way to know if you’re trying to call a games= or if you are trying to set a local variable named games.

This is directly setting an instance variable rather than calling a method.

This sets up both a getter (self.games) and a setter (self.games=) for the named attribute. If you end up defining either of those in the class you will be overriding the one set by this attr_accessor call. attr_accessor :games ends up defining:

def games
  @games
end

def games=(value)
  @games = value
end

(Jon Seidel) #3

Thanks @derekprior; helped clarify things for me.; self.games [the method] works because there was a previous attr_accessor call and, under the covers, it sets @games.

Also, I can see how the different approaches can be used, as in:

attr_accessor : games
attr_reader :user
def initialize :games, :user)
  self.games = games
  @user = user
end

Since I didn’t define a setter for user.