ruby syntactic sugar: dealing with nils

前端 未结 6 1795
天命终不由人
天命终不由人 2021-02-10 02:45

probably asked already but I couldn\'t find it.. here are 2 common situation (for me while programming rails..) that are frustrating to write in ruby:

\"a string         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-10 03:00

    In Ruby on Rails you have the try method available on any Object. According to the API:

    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 for the first question you can do this:

    "a string".match(/abc(.+)abc/).try(:[], 1)
    

    And it will either give you [1] or nil without error.

提交回复
热议问题