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

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

提交回复
热议问题