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

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

    nil? can be omitted in boolean contexts. Generally, you can use this to replicate the C# code:

    return my_string.nil? || my_string.empty?
    
    0 讨论(0)
  • 2020-12-04 08:32

    When I'm not worried about performance, I'll often use this:

    if my_string.to_s == ''
      # It's nil or empty
    end
    

    There are various variations, of course...

    if my_string.to_s.strip.length == 0
      # It's nil, empty, or just whitespace
    end
    
    0 讨论(0)
  • 2020-12-04 08:32

    If you are willing to require ActiveSupport you can just use the #blank? method, which is defined for both NilClass and String.

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

    Check for Empty Strings in Plain Ruby While Avoiding NameError Exceptions

    There are some good answers here, but you don't need ActiveSupport or monkey-patching to address the common use case here. For example:

    my_string.to_s.empty? if defined? my_string
    

    This will "do the right thing" if my_string is nil or an empty string, but will not raise a NameError exception if my_string is not defined. This is generally preferable to the more contrived:

    my_string.to_s.empty? rescue NameError
    

    or its more verbose ilk, because exceptions should really be saved for things you don't expect to happen. In this case, while it might be a common error, an undefined variable isn't really an exceptional circumstance, so it should be handled accordingly.

    Your mileage may vary.

    0 讨论(0)
提交回复
热议问题