rails < 4.0 “try” method throwing NoMethodError?

后端 未结 3 1079
一向
一向 2020-12-13 19:45

Why is try throwing an error? Doesnt that defeat the whole purpose? Maybe its just in the console?

ruby-1.9.2-p180 :101 > User.first.try(:something)
NoMet         


        
3条回答
  •  醉酒成梦
    2020-12-13 20:00

    This is what try does

    Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does. Unlike that method however, a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass.

    So, let's say you setup @user in your controller but you didn't instantiate it then @user.try(:foo) => nil instead of

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

    The important point here is that try is an instance method. It also doesn't return nil if the object you try on isn't nil.

提交回复
热议问题