Converting an empty string to nil in place?

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.


I know I am bit late but you can write your own method for the String class, and run code in initializers:

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

and then you will get:

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

Of course you can also strip the string before checking if thats suits for you


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