加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 为什么Object ::如果发送到nil对象的话会尝试

发布时间:2020-12-17 03:37:41 所属栏目:百科 来源:网络整理
导读:如果您尝试在 Ruby中的nil对象上调用方法,则会出现NoMethodError异常,并显示以下消息: "undefined method ‘...’ for nil:NilClass" 但是,在Rails中有一个 try 方法,如果它被发送到一个nil对象,它只返回nil: require 'rubygems'require 'active_support/a
如果您尝试在 Ruby中的nil对象上调用方法,则会出现NoMethodError异常,并显示以下消息:

"undefined method ‘...’ for nil:NilClass"

但是,在Rails中有一个try方法,如果它被发送到一个nil对象,它只返回nil:

require 'rubygems'
require 'active_support/all'

nil.try(:nonexisting_method) # no NoMethodError exception anymore

那么如何在内部尝试工作以防止该异常呢?

解决方法

ActiveSupport 4.0.0定义了两种try方法: one用于Object实例:

class Object
  def try(*a,&b)
    if a.empty? && block_given?
      yield self
    else
      public_send(*a,&b) if respond_to?(a.first)
    end
  end
end

other适用于NilClass实例(零个对象):

class NilClass
  def try(*args)
    nil
  end
end

现在,假设我们有一个Object实例(不包括nil,它实际上继承自Object,就像Ruby中的其他所有内容一样),定义一个返回nil的方法:

class Test
  def returns_nil
    nil
  end
end

因此,运行Test.new.try(:returns_nil)或Test.new.not_existing_method,将调用Object#try,它将检查是否存在公共方法(respond_to?);如果是这样,它将调用方法(public_send),否则它将返回nil(没有其他行).

如果我们再次尝试这些返回的nil方法:

Test.new.try(:returns_nil).try(:any_other_method)
Test.new.try(:not_existing_method).try(:any_other_method)

我们将调用NilClass#try,这是nil#try,它只是忽略所有内容并返回nil.因此,任何其他尝试都将在nil实例上调用并返回nil.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读