Reputation: 4986
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?
Upvotes: 32
Views: 22589
Reputation: 1258
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
Upvotes: 83
Reputation: 26353
Regex to the rescue! We can use string[regexp]
which returns a new_string
if there is a match or nil
if the regex doesn't match (see documentation String).
''[/.+/]
# => nil
'text'[/.+/]
# => 'text'
# Caution 1: This doesn't work for strings which are just spaces
' '[/.+/]
# => ' '
# In these cases you can strip...
' '.strip[/.+/]
# => nil
# ...or use a more complicated regex:
' '[/.*\S.*/]
# => nil
Upvotes: 1
Reputation: 1801
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
Upvotes: 3
Reputation: 19475
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.
Upvotes: 4