25

为什么尝试抛出错误?这不是破坏了整个目的吗?也许它只是在控制台中?

ruby-1.9.2-p180 :101 > User.first.try(:something)
NoMethodError: undefined method `something' for #<User:0x000001046ad128>
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/activemodel-3.0.10/lib/active_model/attribute_methods.rb:392:in `method_missing'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.10/lib/active_record/attribute_methods.rb:46:in `method_missing'
    from (irb):101
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in `start'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in `start'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

编辑:

谢谢各位,现在我明白了。

有没有一种方法可以在不使用 using 的情况下执行我想要的操作respond_to?,从而User.try(:something)返回nil而不是抛出错误?

4

3 回答 3

58

导轨 3

try您从精美的手册中误解了工作原理:

try(*a, &b)
调用由符号方法标识的方法,将任何参数和/或指定的块传递给它,就像常规 RubyObject#send所做的那样。

然而,与该方法不同的是NoMethodErrornil如果接收对象是nil对象或NilClass.

并且该版本try被修补为NilClass

try(*args)调用
总是返回trynilnil

因此try,不要忽略您尝试调用对象上不存在的方法的尝试,它会忽略您尝试调用方法nil并返回nil而不是引发异常。该try方法只是一种避免nil在方法调用链中的每一步都检查的简单方法。


导轨 4

的行为try在 Rails 4 中发生了变化,所以现在它:

调用名称作为第一个参数的公共方法public_send,只是如果接收者没有响应它,则调用返回nil而不是引发异常。

所以现在try同时处理这两项检查。如果你想要 Rails 3 的行为,有try!

与 相同,但如果接收 [sic] 不是并且没有实现 [sic] 尝试的方法try,则会引发异常。NoMethodErrornil

于 2011-09-15T06:45:26.513 回答
8

这就是尝试所做的

调用由符号方法标识的方法,将任何参数和/或指定的块传递给它,就像常规的 Ruby Object#send 一样。然而,与该方法不同的是,如果接收对象是 nil 对象或 NilClass,则不会引发 NoMethodError 异常,而是返回 nil。

因此,假设您@user在控制器中进行了设置,但您没有实例化它@user.try(:foo) => nil而不是

@user.foo
NoMethodError: undefined method `foo' for nil:NilClass

这里重要的一点是 try 是一个实例方法。如果您尝试的对象不是 nil ,它也不会返回 nil

于 2011-09-15T06:47:28.073 回答
5

我知道这是旧的,但它可能对其他人有帮助,因为这是我在谷歌上搜索这个问题时出现的第一件事。我“借用”了try的代码并实现了我自己的try_method方法,它的作用就像try一样,只是它在调用send之前首先检查该方法是否存在。我在 Object 中实现了它并将其放入初始化程序中,现在我可以在任何对象上调用它。

class Object
  # Invokes the method identified by _method_, passing it any
  # arguments specified, just like the regular Ruby <tt>Object#send</tt> does.
  #
  # *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
  # if the method does not exist.
  #
  # This differs from the regular Ruby <tt>Object#try</tt> method which only
  # suppresses the +NoMethodError+ exception if the object is Nil
  #
  # If try_method is called without a method to call, it will yield any given block with the object.
  #
  # Please also note that +try_method+ is defined on +Object+, therefore it won't work with
  # subclasses of +BasicObject+. For example, using try_method with +SimpleDelegator+ will
  # delegate +try_method+ to target instead of calling it on delegator itself.
  #
  # ==== Examples
  #
  # Without +try_method+
  #   @person && @person.respond_to?(:name) && @person.name
  # or
  #   (@person && @person.respond_to?(:name)) ? @person.name : nil
  #
  # With +try_method+
  #   @person.try_method(:name)
  #
  # +try_method+ also accepts arguments and/or a block, for the method it is trying
  #   Person.try_method(:find, 1)
  #   @people.try_method(:collect) {|p| p.name}
  #
  # Without a method argument try_method will yield to the block unless the receiver is nil.
  #   @person.try_method { |p| "#{p.first_name} #{p.last_name}" }
  #--
  # +try_method+ behaves like +Object#send+, unless called on +NilClass+ or a class that does not implement _method_.
  def try_method(method=nil, *args, &block)
    if method == nil && block_given?
      yield self
    elsif respond_to?(method)
      __send__(method, *args, &block)
    else
      nil
    end
  end
end

class NilClass
  # Calling +try_method+ on +nil+ always returns +nil+.
  # It becomes specially helpful when navigating through associations that may return +nil+.
  #
  # === Examples
  #
  #   nil.try_method(:name) # => nil
  #
  # Without +try_method+
  #   @person && @person.respond_to(:children) && !@person.children.blank? && @person.children.respond_to(:first) && @person.children.first.respond_to(:name) && @person.children.first.name
  #
  # With +try_method+
  #   @person.try_method(:children).try_method(:first).try_method(:name)
  def try_method(*args)
    nil
  end
end
于 2012-08-25T06:38:46.163 回答