简体   繁体   中英

NameError: uninitialized constant Game

I have a file Word.rb

class Word

attr_accessor :word, :letters

    def initialize (word)
        #@word = word
        @letters = word.split('').map{|letter| {:letter => letter, :hidden => true} }
    end

end

and another file Game.rb, which will use Word.rb

require_relative ('./Word.rb') 
require 'pry'

class Game 

attr_accessor :guesses, :guessed_letters, :words, :current_word

    def initialize (words)
        @guesses = 0
        @guessed_letters = []
        @words = words
        @current_word = current_word
    end
end

And I'm getting the following error:

NameError: uninitialized constant Game

When I try to create a instance of Game like this:

game = Game.new(['hello', 'sunshine', 'chipmunk', 'twitch'])

I just am not sure what I am doing wrong since I am requiring the Word.rb file that Game.rb will need. All files are on the same level, nothing is in a subdirectory. Interestingly, I do not get this error once I comment the require_relative line out (but of course, I need that file required). I have also tried not using require_relative and simply using require as well as a couple other varieties: parens/no parens, file extension/no file extension, etc. How do I properly require this file? I also have a lovely and robust array of words sitting in another file that I would like to require to be used and passed into Game.new() .

Look What I did

$ mkdir test
$ cd test
$ gedit Word.rb
# and copied your content and saved
$ gedit Game.rb
# and copied you content and saved
$ irb

After IRB session run I did following

2.1.1 :001 > game = Game.new(['asd'])
NameError: uninitialized constant Game
    from (irb):1
    from /home/shiva/.rvm/rubies/ruby-2.1.1/bin/irb:11:in `<main>'
2.1.1 :002 > require 'game'
LoadError: cannot load such file -- game

2.1.1 :004 > require 'Game.rb'
LoadError: cannot load such file -- Game.rb

2.1.1 :005 > require './Game.rb'
 => true 
2.1.1 :006 > game = Game.new(['shiva', 'bhusal'])
 => #<Game:0x00000003085428 @guesses=0, @guessed_letters=[], @words=["shiva", "bhusal"], @current_word=nil> 
2.1.1 :007 >

Try like this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM