Rubyクラスの初期化されていない定数エラー
概要
RubyMine には次の 2 つのクラスがあります。
本.rb:
class Book
def initialize(name,author)
end
end
テスト.rb:
require 'book'
class teste
harry_potter = Book.new("Harry Potter", "JK")
end
test.rb を実行すると、次のエラーが発生します。
C:/Users/DESKTOP/RubymineProjects/learning/test.rb:3:in `<class:Test>': uninitialized constant Test::Book (NameError)
from C:/Users/DESKTOP/RubymineProjects/learning/test.rb:1:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
解決策
require ‘book’ 行が他の場所からの他の book.rb を要求しているためにエラーが発生しますが、これは Book クラスを定義していません。
Ruby は、require を検索するディレクトリのリストに現在のディレクトリを自動的に含めないため、現在のディレクトリ内のファイルを require する場合は、明示的に ./ を先頭に追加する必要があります。
require './book'