Ruby << (double less) with instance variables

I am not sure how this is valid code:

class Library
  def initialize(games)
    @games = games
  end

  def add_game(game)
    games << game
  end

  def games()
    @games
  end
end

games = ['WoW','SC2','D3']
lib = Library.new(games)
puts lib.games
lib.add_game('Titan')
puts lib.games

This will print:

WoW SC2 D3 Titan

I think he should print

WoW SC2 D3

The add_game method does not use an instance variable. Being new to Ruby, I don't understand how this works. It should not be:

def add_games(game)
  @games << game
end

I am reading this from a tutorial, and I could not find anything about how <<<works specifically with instance variables. I thought: “<<was just overloaded when working with arrays to“ add to the array. ”Does this really do something with Singleton classes?

+5
source share
2 answers

This code is a bit confusing. Line:

games << game

games, @games. <<. Ruby << , , .

:

:

(games).<< game

:

(self.games).<< game

(self.games) << game

games.

+6

, :

class Library
  def initialize(manygames)
    @games = manygames
  end

  def add_game(game)
    imlookingforclassinstancevariable << game
  end

  def imlookingforclassinstancevariable
    @games #i'm the final storage of your array
  end
end
games = ['WoW','SC2','D3']
lib = Library.new(games)
puts lib.imlookingforclassinstancevariable
lib.add_game('Titan')
puts lib.imlookingforclassinstancevariable
0

All Articles