I'm looking for a way to convert an empty string to nil
in place using Ruby. If I end up with a string that is empty spaces I can do
" ".strip!
This will give me the empty string ""
.
What I would like to be able to do is something like this.
" ".strip!.to_nil!
This will get an in place replacement of the empty string with nil
. to_nil!
would change the string to nil
directly if it is .empty?
otherwise if the string is not empty it would not change.
The key here is that I want it to happen directly rather than through an assignment such as
f = nil if f.strip!.empty?
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.
A string refers to a character's sequence. Sometimes strings can be empty or NULL. The difference is that NULL is used to refer to nothing. However, an empty string is used to point to a unique string with zero length.
nil is an Object, NULL is a memory pointer Sadly, when this happens, Ruby developers are confusing a simple little Ruby object for something that's usually radically different in “blub” language. Often, this other thing is a memory pointer, sometimes called NULL, which traditionally has the value 0.
“A null String is Java is literally equal to a reserved word “null”. It means the String that does not point to any physical address.” In Java programming language, a “null” String is used to refer to nothing. It also indicates that the String variable is not actually tied to any memory location.
The clean way is using presence
.
Let's test it.
' '.presence # => nil ''.presence # => nil 'text'.presence # => "text" nil.presence # => nil [].presence # => nil {}.presence # => nil true.presence # => true false.presence # => nil
Please note this method is from Ruby on Rails v4.2.7 https://apidock.com/rails/Object/presence
That isn't possible.
String#squeeze!
can work in place because it's possible to modify the original object to store the new value. But the value nil
is an object of a different class, so it cannot be represented by an object of class String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With