IT

Ruby에서 문자열의 Nil 또는 Length == 0을 확인하는 더 좋은 방법이 있습니까?

lottoking 2020. 5. 27. 07:44
반응형

Ruby에서 문자열의 Nil 또는 Length == 0을 확인하는 더 좋은 방법이 있습니까?


Ruby에서 문자열이 0인지 또는 길이가 0인지 확인하는 다음보다 나은 방법이 있습니까?

if !my_string || my_string.length == 0
  return true
else
  return false
end

C #에는 편리한 것이 있습니다

string.IsNullOrEmpty(myString)

루비와 비슷한 점이 있습니까?


성능에 대해 걱정하지 않으면 다음을 자주 사용합니다.

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

물론 다양한 변형이 있습니다 ...

if my_string.to_s.strip.length == 0
  # It's nil, empty, or just whitespace
end

ActiveSupport가 필요하면 #blank?NilClass와 String 모두에 대해 정의 된 메소드를 사용하면 됩니다.


나는 이것을 Rails / ActiveSupport가 아닌 환경에서 다음과 같이하고 싶다 :

variable.to_s.empty?

이것은 다음과 같은 이유로 작동합니다.

nil.to_s == ""
"".to_s == ""

jcoby의 제안에 대한 대안은 다음과 같습니다.

class NilClass
  def nil_or_empty?
    true
  end
end

class String
  def nil_or_empty?
    empty?
  end
end

Rails (ActiveSupport)가 편리한 공백을 갖기 전에 여기에서 말했듯이 ? 메소드와 다음과 같이 구현됩니다.

class Object
  def blank?
    respond_to?(:empty?) ? empty? : !self
  end
end

루비 기반 프로젝트에 쉽게 추가 할 수 있습니다.

이 솔루션의 장점은 문자열뿐만 아니라 배열 및 기타 유형에서도 자동으로 작동한다는 것입니다.


variable.blank? 할 것입니다. 문자열이 비어 있거나 문자열이 nil이면 true를 리턴합니다.


nil?부울 컨텍스트에서는 생략 할 수 있습니다. 일반적으로 이것을 사용하여 C # 코드를 복제 할 수 있습니다.

return my_string.nil? || my_string.empty?

우선, 그 방법에주의하십시오 :

제시 Ezel는 말합니다 :

브래드 아브람

"이 방법은 편리해 보이지만 대부분의 경우이 상황은 더 깊은 버그를 해결하려고 시도 할 때 발생합니다.

코드는 문자열 사용시 특정 프로토콜을 고수해야하며 라이브러리 코드 및 작업중인 코드에서 프로토콜 사용을 이해해야합니다.

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

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.


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

(my_string||'').empty?


Konrad Rudolph has the right answer.

If it really bugs you, monkey patch the String class or add it to a class/module of your choice. It's really not a good practice to monkey patch core objects unless you have a really compelling reason though.

class String
  def self.nilorempty?(string)
    string.nil? || string.empty?
  end
end

Then you can do String.nilorempty? mystring


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.


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?

For code golfers (requires ruby 2.3 or later):

if my_string&.> ""
  p 'non-empty string'
else
  p 'nil or empty string'
end

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.

참고URL : https://stackoverflow.com/questions/247948/is-there-a-better-way-of-checking-nil-or-length-0-of-a-string-in-ruby

반응형