Converting an empty string to zero?

I am looking for a way to convert an empty string to zero in place using Ruby. If I get a string that is empty space, I can do

" ".strip! 

This will give me an empty string "".

What I would like to do is something like this.

 " ".strip!.to_nil! 

This will replace the empty string with nil. to_nil! will change the string to nil directly if it is empty? otherwise, if the line is not empty, it will not change.

The key point here is that I want this to happen directly, and not through an assignment such as

 f = nil if f.strip!.empty? 
+4
source share
3 answers

The clean way is presence .

Test it out.

 " ".presence # => nil "".presence # => nil "text".presence # => "text" nil.presence # => nil [].presence # => nil 

Please note that this method applies to Ruby on Rails v4.2.7 https://apidock.com/rails/Object/presence

+3
source

It's impossible.

String#squeeze! can work in place because you can modify the original object to store the new value. But nil is an object of another class, so it cannot be represented by an object of class String .

+3
source

I know I'm a little late, but you can write your own method for the String class and run the code in the initializers:

 class String def to_nil present? ? self : nil end end 

and then you get:

 'a'.to_nil => "a" ''.to_nil => nil 

Of course, you can also delete the line before checking if this is right for you.

+2
source

Source: https://habr.com/ru/post/1469354/


All Articles