Ruby比较错误.确定a == b,a> b时出错

jxx*_*son 0 ruby comparison-operators

如果我在比较中将==更改为>,则会在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
Run Code Online (Sandbox Code Playgroud)

以下是导致投诉的方法定义.看到这条线

if line.index("<item>") > -1
Run Code Online (Sandbox Code Playgroud)

同

if line.index("<item>") == 0
Run Code Online (Sandbox Code Playgroud)

有用.失败> 0也.

Yuuk!

  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
Run Code Online (Sandbox Code Playgroud)

ilt*_*mpo 5

你的line.index("<item>")评价是nil.Nil有一种==方法,但没有>.所以根本原因在于nil你有一个你没想到的地方.