Here is my code i am using ruby

96 views Asked by At

it keeps on saying syntax error unexpected ' n' expecting :: [' or '.' and syntax error unexpected keyword_ensure expecting end-of-input. what is the problem with my code?

require 'rubygems'
require 'rubygame'

class
      def initialize
             @screen = Rubygame::Screen.new [640, 480], 0, [Rubygame::HWSURFACE, Rubygame::DOUBLEBUF] 
             @screen.title = "Pong"

             @queue = Rubygame::EventQueue.new
             @clock =  Rubygame::Clock.new
             @clock.target_framerate = 60
      end

      def run!
          loop do
                      update
                      draw
                      @clock.tick
           end  
      end

      def update
      end

      def draw
      end
end

g = Game.new
g.run!
3

There are 3 answers

0
yan On

You don't have a class name, just the keyword 'class'.

0
the Tin Man On
class

should be:

class Game

That will get you started.

Stylistically, your code is formatted wrong for Ruby:

  • Use 2-space indenting
  • It's smart to use trailing () after a method name: It visually sets it apart when you're reading it, and there are occasions where Ruby will misunderstand and think a method is a variable until its seen a definite method vs. variable use of that name.
  • Use parenthesis to surround the parameters for methods like:

    @screen = Rubygame::Screen.new [640, 480], 0, [Rubygame::HWSURFACE, Rubygame::DOUBLEBUF] 
    

    You can encounter a world of debugging-hurt if you try to pass a block to a method call without surrounding parameters. Ruby will be confused and will throw errors; Simply getting in the habit of surrounding them will avoid the problem cleanly and without fuss.

0
JTigger On

So, this is a really cryptic error message because there's a fundamental syntax error in your code!

As other have noted, the problem is the missing classname. That is, line 4, instead of this:

class

should be this:

class Game

But why? And how did we know it should be "Game"?

In Ruby, you usually include an name after the "class" keyword. It's using this name that you can create objects based off this class definition. This is what's happening in the second-to-last line in your program:

g = Game.new

This line says, "create a new instance of the 'Game' class and assign that to the variable 'g'." In order for this line to actually work, there needs to be a class by the name of "Game". This is our clue for what the name of this class should be.

You're clearly getting over the initial hump in learning Ruby. Keep at it! It starts to get easier as you're able to get more syntax under your belt.

Good luck!