ruby syntactic sugar: dealing with nils

前端 未结 6 1793
天命终不由人
天命终不由人 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 02:59

    "a string".match(/foo(bar)/).to_a[1]
    

    NilClass#to_a returns an empty array, and indexing outside of it gives you nil values.

    Alternatively (what I do) you can splat the matches:

    _, some, more = "a string".match(/foo(bar)(jim)/).to_a
    

提交回复
热议问题