Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

后端 未结 16 1280
夕颜
夕颜 2020-12-04 07:57

Is there a better way than the following to check to see if a string is nil OR has a length of 0 in Ruby?

if !my_str         


        
16条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 08:24

    If you are using rails, you can use #present?

    require 'rails'
    
    nil.present?  # ==> false (Works on nil)
    ''.present?    # ==> false (Works on strings)
    '  '.present?  # ==> false (Works on blank strings)
    [].present?    # ==> false(Works on arrays)
    false.present? # ==> false (Works on boolean)
    

    So, conversely to check for nil or zero length use !present?

    !(nil.present?)  # ==> true
    !(''.present?)    # ==> true
    !('  '.present?)  # ==> true
    !([].present?)    # ==> true
    !(false.present?) # ==> true
    

提交回复
热议问题