Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for empty or nil-value string [duplicate]

People also ask

How do you check if a string is nil or not?

nil coalescing operator returns the left side if it's non-nil, otherwise it returns the right side. You can also use it like this to return a default value: (string ?? "").

Is empty string nil Ruby?

nil? will only return true if the object itself is nil. That means that an empty string is NOT nil and an empty array is NOT nil.


The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.


If you're in Rails, .blank? should be the method you are looking for:

a = nil
b = []
c = ""

a.blank? #=> true
b.blank? #=> true
c.blank? #=> true

d = "1"
e = ["1"]

d.blank? #=> false
e.blank? #=> false

So the answer would be:

variable = id if variable.blank?

variable = id if variable.to_s.empty?