ruby syntactic sugar: dealing with nils

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

    "a string"[/abc(.+)abc/, 1]
    # => nil
    "abc123abc"[/abc(.+)abc/, 1]
    # => "123"
    

    And:

    var = something.very.long.and.tedious.to.write || something.other
    

    Please note that or has a different operator precedence than || and || should be preferred for this kind of usage. The or operator is for flow control usage, such as ARGV[0] or abort('Missing parameter').

提交回复
热议问题