【问题标题】:Comparing CSV::Row objects to singleton nil vs using nil?将 CSV::Row 对象与单例 nil 与使用 nil 进行比较?
【发布时间】:2013-08-22 18:33:26
【问题描述】:

所以我在 Ruby 1.9.3-p374 中生成了一个包含 CSV::Row 对象和 nil 的数组,如下所示:

 csv_array = [nil, #<CSV::Row "name":John>, nil, nil, #<CSV::Row "name":John>]

以下代码行正常工作:

 csv_array.delete_if { |x| x.nil? }

但是这一行给出了一个错误:

 csv_array.delete_if { |x| x==nil }

错误:

.rvm/rubies/ruby-1.9.3-p374/lib/ruby/1.9.1/csv.rb:478:in `==': undefined method `row' for nil:NilClass (NoMethodError)

关于为什么会这样的任何想法?我认为==nil.nil? 会产生相同的结果。

【问题讨论】:

  • 我认为错误出在其他地方..请检查您的代码..
  • 请给我们完整的堆栈跟踪..我非常确定错误在其他地方..

标签: ruby csv ruby-1.9.3


【解决方案1】:

CSV::Row 覆盖 == 并且实现假定您要与之比较的对象也是 CSV::Row。如果你将任何不属于该类的东西传递给它,它可能会爆炸。

您可能会争辩说这是不好的做法,在这种情况下它应该返回 false 而不是炸毁(这在 ruby​​ 2.0 中似乎已更改)

另一方面,nil? 没有被覆盖,因此可以按您的预期工作。

【讨论】:

【解决方案2】:

我认为 ==nil 和 .nil?会产生相同的结果。

是的,他们正在给予。看我下面的例子:

require 'csv'

c1 = CSV::Row.new(["h1","h2","h3"],[1,2,3])
# => #<CSV::Row "h1":1 "h2":2 "h3":3>
c2 = CSV::Row.new(["h1","h3","h4"],[1,2,3])
# => #<CSV::Row "h1":1 "h3":2 "h4":3>
[nil,c1,c2].delete_if { |x| x.nil? }
# => [#<CSV::Row "h1":1 "h2":2 "h3":3>, #<CSV::Row "h1":1 "h3":2 "h4":3>]
[nil,c1,c2].delete_if { |x| x==nil }
# => [#<CSV::Row "h1":1 "h2":2 "h3":3>, #<CSV::Row "h1":1 "h3":2 "h4":3>]
c1.respond_to?(:nil?) # => true
c1.respond_to?(:==) # => true
c1==nil # => false
c1.nil? # => false

您怀疑是错误的代码是完美的。但是从'==': undefined method 'row' for nil:NilClass (NoMethodError) 行可以清楚地看出,您在代码something == something.row 中的其他地方使用了一些somethingnil。因此你得到了错误,因为NilClass 没有任何#row 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    相关资源
    最近更新 更多