-3

我正在为 Ruby 中的 CS 作业编写此代码。我刚开始使用 Ruby,所以我不太了解它,但我不断从这段代码中得到一个 no method 错误,如下所示:

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
4

1 回答 1

1

线索在错误信息中!

undefined method line

在您的 while 循环中,您正在从filevia读取一行gets,然后将其存储在line. 这段代码:

if(file.line.reverse == file.line)

因此是不正确的——你不需要file.前缀!Ruby 认为您正在尝试调用它没有line的对象的方法。file这就是为什么它给你它所做的错误......</p>

于 2012-04-25T23:43:41.367 回答