Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an empty string to nil in place?

Tags:

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? 
like image 497
bigtunacan Avatar asked Mar 14 '13 20:03

bigtunacan


People also ask

Is empty string nil?

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.

Can a string be a null?

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.

Is nil the same as null Ruby?

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.

How to define null string?

“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.


2 Answers

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

like image 56
Komsun K. Avatar answered Oct 21 '22 11:10

Komsun K.


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.

like image 26
qqx Avatar answered Oct 21 '22 10:10

qqx