我正在学习Ruby,最近完成了一个创建目录的任务.但是,代码可以在代码结束时发生以下错误:
table_of_contents2.rb:23:in `<main>': undefined method `ljust' for nil:NilClass (NoMethodError)
Run Code Online (Sandbox Code Playgroud)
我仔细检查过该大纲变量不是nil做一个puts outlinewhile循环中,并试图改变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
Run Code Online (Sandbox Code Playgroud)
为什么会出现此错误?为什么在代码成功运行后会发生这种情况?
附录:我在终端中运行代码.运行代码时终端内的完整显示如下:
$ 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)
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助!
问题在于此while j <= outline.length.
它应该是while j < outline.length.
但是,在Ruby中,手动维护游标通常被认为是一种不好的做法.您的程序可以重写为
line_width = 40
chapters = ["Chapter 1: Numbers", "Chapter 2: Letters",
"Chapter 3: Variables"]
pages = ["page 1","page 72","page 118"]
puts "Table of Contents".center line_width
chapters.zip(pages).each do |chapter, page|
puts chapter.ljust(line_width/2) + page.rjust(line_width/2)
end
Run Code Online (Sandbox Code Playgroud)
顺便说一句,Ruby程序员喜欢强调以驼峰(除了类名和模块名),所以我改lineWidth到line_width.