私はRubyを学び、最近目次を作成する課題を完了しました。コードが動作する、しかし、コードの末尾に、次のエラーが発生します。未定義メソッド `ljust 'for nil:NilClass(NoMethodError)
table_of_contents2.rb:23:in `<main>': undefined method `ljust' for nil:NilClass (NoMethodError)
私は二重のアウトライン変数は、whileループ内puts outline
を行うことによってnil
ではないことを確認し、変更してみましたoutline
をコード全体で@outline
と$outline
に変更できますが、エラーは持続しています。
完全なコードは以下の通りです:
lineWidth = 40
chapters = ["Chapter 1: Numbers", "Chapter 2: Letters",
"Chapter 3: Variables"]
pages = ["page 1","page 72","page 118"]
puts "Table of Contents".center lineWidth
outline = []
i = 0
while i < 3
outline.push(chapters[i])
outline.push(pages[i])
i = i + 1
end
j = 0
while j <= outline.length
puts outline[j].ljust(lineWidth/2) +
outline[j+1].rjust(lineWidth/2)
j = j + 2
end
はなぜこのエラーが発生していますか?そして、コードが正常に実行された後、なぜそれが起こっていますか?
補足:ターミナルでコードを実行しています。コードを実行するときの端末内での完全な表示は、次のとおりです。
$ ruby table_of_contents2.rb
Table of Contents
Chapter 1: Numbers page 1
Chapter 2: Letters page 72
Chapter 3: Variables page 118
table_of_contents2.rb:23:in `<main>': undefined method `ljust' for nil:NilClass (NoMethodError)
ありがとうございました!
「<」または「outline.length - 1」のいずれかを使用します。どちらも使用する必要はありません。 –
私の答えを更新しました。ありがとう –