Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby << (double less than) with instance variables

Tags:

ruby

I'm 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 out:

WoW SC2 D3 Titan

I would think that it should print out

WoW SC2 D3

The add_game method doesn't use the instance variable. Being new to Ruby, I don't understand how this works. Shouldn't it have to be:

def add_games(game)
  @games << game
end

I'm reading this from a tutorial and I haven't been able to find anything on how << works specifically with instance variables. I thought '<<' was just overloaded when dealing with arrays to be 'append to the array'. Is this actually doing something w/ Singleton classes?

like image 456
sjmh Avatar asked Mar 12 '13 21:03

sjmh


1 Answers

This code is a little confusing. The line:

games << game

is actually calling the method games, which returns @games. Then the << method is called on that result. There's some syntactic sugar in the Ruby parser that turns the << operator into a method call on the left operand, and the left operand is being evaluated before that happens.

Edit for more clarity:

The line could be written like this:

(games).<< game

or this:

(self.games).<< game

or:

(self.games) << game

all of which execute the games method.

like image 139
Jim Stewart Avatar answered Oct 21 '22 04:10

Jim Stewart