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

后端 未结 16 1243
夕颜
夕颜 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:23

    For code golfers:

    if my_string=~/./
      p 'non-empty string'
    else
      p 'nil or empty string'
    end
    

    Or if you're not a golfer (requires ruby 2.3 or later):

    if my_string&.size&.positive?
      # nonzero? also works
      p 'non-empty string'
    else
      p 'nil or empty string'
    end
    

提交回复
热议问题