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

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

    First of all, beware of that method:

    As Jesse Ezel says:

    Brad Abrams

    "The method might seem convenient, but most of the time I have found that this situation arises from trying to cover up deeper bugs.

    Your code should stick to a particular protocol on the use of strings, and you should understand the use of the protocol in library code and in the code you are working with.

    The NullOrEmpty protocol is typically a quick fix (so the real problem is still somewhere else, and you got two protocols in use) or it is a lack of expertise in a particular protocol when implementing new code (and again, you should really know what your return values are)."

    And if you patch String class... be sure NilClass has not been patch either!

    class NilClass
        def empty?; true; end
    end
    

提交回复
热议问题