【问题标题】:Ruby comparison error. OK with a == b, error on a > b红宝石比较错误。 a == b 正常,a > b 出错
【发布时间】:2012-02-19 10:39:58
【问题描述】:

如果我在比较中将 == 更改为 >,我会在 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

【问题讨论】:

    标签: ruby comparison-operators


    【解决方案1】:

    您的 line.index("&lt;item&gt;") 计算结果为 nil。 Nil 有一个== 方法,但没有&gt;。所以根本原因是你没想到的地方有nil。

    【讨论】:

    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2014-03-29
    • 2021-10-06
    • 1970-01-01
    相关资源
    最近更新 更多