0

如果我在比较中将 == 更改为 >,我会在 ruby​​ 中收到以下错误:

nano:jc] ruby ItemController.rb

file read: snippets.txt

ItemController.rb:23:in `read': undefined method `>' for nil:NilClass (NoMethodError)
    from ItemController.rb:19:in `open'
    from ItemController.rb:19:in `read'
    from ItemController.rb:58

以下是引起投诉的方法定义。看线

if line.index("<item>") > -1

if line.index("<item>") == 0

有用。> 0 也失败。

优克!

  def read
    @item_count = 0
    File.open(@file_name, 'r') do |f1|
      while line=f1.gets
        @line.concat([line])

        if line.index("<item>") > -1
          puts "begin"
          @item_count = @item_count + 1
        end

        if line.index("</item>") == 0 
          puts "end\n"

        end

        # puts line
      end # while
   end # do
  end # def
4

1 回答 1

5

您的line.index("<item>")评估结果为nil。Nil 有一个==方法,但没有>。所以根本原因是有一个nil你没想到的地方。

于 2012-02-19T10:49:40.137 回答