我正在为Ruby中的CS赋值编写此代码。我刚刚开始使用Ruby,所以我对它并不了解,但我不断从这段代码中得到一个no方法错误:
V:\CS 300 RubyAssignment\lib\rubyAssignment.rb:13:in `categorize': undefined method `line' for #<File:ruby1.txt (closed)> (NoMethodError)
from V:\CS 300 RubyAssignment\lib\rubyAssignment.rb:11:in `open'
from V:\CS 300 RubyAssignment\lib\rubyAssignment.rb:11:in `categorize'
from V:\CS 300 RubyAssignment\lib\rubyAssignment.rb:30
代码如下,但我感觉我的文本文件位于错误的位置。我使用NetBeans Ruby插件,我不知道我的文本文件是否应该在netbeans中的项目源文件夹,测试文件夹或库文件夹中?它可能就像任何想法一样简单吗?
# This program reads a file line by line,
# separating lines by writing into certain text files.
# PPQ - Pangrams, Palindromes, and Quotes
class PPQ
def categorize
file_pangram = File.new('pangram.txt', 'w')
file_palindrome = File.new('palindrome.txt', 'w')
file_quotes = File.new('quotes.txt','w')
File.open('ruby1.txt','r') do |file|
while line = file.gets
if(file.line.reverse == file.line)
file_palindrome.write line
if(file.line.contains('a'&&'b'&&'c'&&'d'&&'e'&&'f'&&'g'&&'h'&&'i'&&'j'&&'k'&&'l'&&'m'&&'n'&&'o'&&'p'&&'q'&&'r'&&'s'&&'t'&&'u'&&'v'&&'w'&&'x'&&'y'&&'z'))
file_pangram.write "file.line"
else
file_quotes.write "file.line"
end
end
end
file.close
file_pangram.close
file_palindrome.close
file_quotes.close
end
end
end
my_ruby_assignment = PPQ.new
my_ruby_assignment.categorize
答案 0 :(得分:1)
错误消息中的线索!
undefined method line
在您的while循环中,您正在通过file
从gets
读取一行,然后将其存储在line
中。这段代码:
if(file.line.reverse == file.line)
因此不正确 - 您不需要file.
前缀! Ruby认为你试图调用它没有的line
对象的file
方法。这就是为什么它给你的错误...