Towers of Hanoi / How do I interpret error messages?

I was able to pass all the specs for the Towers of Hanoi but it’s not playable. I get a bunch of error messages and I don’t really know what to make of them.

This is my code:

class TowersOfHanoi
  attr_accessor :towers
  def initialize
    @towers = [[3, 2, 1], [], []]
  end

  def play
    puts render
    until won?
      puts "Which pile would you like to select a disc from?"
      from_tower = gets.to_i

      puts "Which pile would you like to put the disc on?"
      to_tower = gets.to_i

      if valid_move?(from_tower, to_tower)
        move(from_tower, to_tower)
      else
        puts "The move is not valid"
      end
    end

    puts "You won!!!!!"
  end

  def render
    puts @towers
  end

  def won?
    if @towers == [[], [3, 2, 1], []] || @towers == [[], [], [3, 2, 1]]
      return true
    end
    false
  end

  def valid_move?(from_tower, to_tower)
    if @towers[from_tower].empty?
      return false
    elsif @towers[to_tower].empty?
      return true
    elsif @towers[from_tower].last < @towers[to_tower].last
      return true
    else
      false
    end
  end

  def move(from_tower, to_tower)
    @towers[to_tower] << @towers[from_tower].pop
  end
end

if $PROGRAM_NAME == __FILE__
    TowersOfHanoi.new.play
end

and these are the error messages I get

Joshs-MacBook-Pro:#{Josh}#{Choi}#{Towers Of Hanoi} JoshC$ lib/towers_of_hanoi.rb
lib/towers_of_hanoi.rb: line 42: class: command not found
lib/towers_of_hanoi.rb: line 43: attr_accessor: command not found
lib/towers_of_hanoi.rb: line 44: def: command not found
lib/towers_of_hanoi.rb: line 45: @towers: command not found
lib/towers_of_hanoi.rb: line 46: end: command not found
lib/towers_of_hanoi.rb: line 48: def: command not found
lib/towers_of_hanoi.rb: line 49: puts: command not found
lib/towers_of_hanoi.rb: line 57: syntax error near unexpected token from_tower,' lib/towers_of_hanoi.rb: line 57: if valid_move?(from_tower, to_tower)’
Joshs-MacBook-Pro:#{Josh}#{Choi}#{Towers Of Hanoi} JoshC$

I tried going thorugh each line that’s mentioned in the error messages but couldn’t find anything wrong with them.

Hi Josh, it looks like you’re running the file directly from the command line, which should work, but it looks to me like your bash shell doesn’t know what to do with the ruby code.
Do you run into the same errors when you load the file in pry and initialize then play a new instance of it?

This is the error message I get when I try to load my towers_of_hanoi.rb

Hi Josh,

By initialize, I meant creating a new instance by running TowersOfHanoi.new

You can save that to a variable like so:
x = TowersOfHanoi.new and then x.play
Or you can type it like you have towards the bottom of your code.

Edit: just realized that your file wasn’t running because you weren’t telling your terminal what to run it with. can you try typing ruby #{your_filename.rb} to see if that works?

1 Like

I was able to run the game! Thanks!