jxxcarlson
jxxcarlson

Reputation: 333

Ruby comparison error. OK with a == b, error on a > b

I get the following error in ruby if I change == to > in a comparison:

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

Below is the method definition that is causing the complaint. See the line

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

With

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

it works. Fails with > 0 also .

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

Upvotes: 0

Views: 115

Answers (1)

iltempo
iltempo

Reputation: 16012

Your line.index("<item>") evaluates to nil. Nil has a == method but there is no >. So the root cause is that there is a nil where you didn't expect it.

Upvotes: 5

Related Questions