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

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

    variable.blank? will do it. It returns true if the string is empty or if the string is nil.

    0 讨论(0)
  • 2020-12-04 08:11

    Every class has a nil? method:

    if a_variable.nil?
        # the variable has a nil value
    end
    

    And strings have the empty? method:

    if a_string.empty?
        # the string is empty
    }
    

    Remember that a string does not equal nil when it is empty, so use the empty? method to check if a string is empty.

    0 讨论(0)
  • 2020-12-04 08:14

    Another option is to convert nil to an empty result on the fly:

    (my_string||'').empty?

    0 讨论(0)
  • 2020-12-04 08:15

    I like to do this as follows (in a non Rails/ActiveSupport environment):

    variable.to_s.empty?
    

    this works because:

    nil.to_s == ""
    "".to_s == ""
    
    0 讨论(0)
  • 2020-12-04 08:15

    In rails you can try #blank?.

    Warning: it will give you positives when string consists of spaces:

    nil.blank? # ==> true
    ''.blank? # ==> true
    '  '.blank? # ==> true
    'false'.blank? # ==> false
    

    Just wanted to point it out. Maybe it suits your needs

    UPD. why am i getting old questions in my feed? Sorry for necroposting.

    0 讨论(0)
  • 2020-12-04 08:18

    Have you tried Refinements?

    module Nothingness
      refine String do
        alias_method :nothing?, :empty?
      end
    
      refine NilClass do
        alias_method :nothing?, :nil?
      end
    end
    
    using Nothingness
    
    return my_string.nothing?
    
    0 讨论(0)
提交回复
热议问题