我正在爲Ruby中的CS任務編寫此代碼。我剛開始在Ruby中,所以我不很瞭解,但我一直從這個像這樣的代碼得到一個無方法錯誤:爲什麼我的程序不能找到我想打開的文本文件?
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
你爲什麼認爲這不是你的文件?你真的看過錯誤信息嗎? – geekosaur 2012-04-25 23:35:59
基本上讓我的問題更簡單,我的文本文件應該放在我的機器上,以便netbeans可以運行此代碼?我需要指定ruby1.txt的目錄還是隻需調用ruby1.txt? – 2012-04-25 23:43:32
它與文件的位置無關,請參閱我的答案... – andrewdotnich 2012-04-25 23:44:06