Converting an Empty String into Nil in Ruby

Converting an empty string to nil in place?

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

Converting an empty string into nil in Ruby

If you're not ashamed of monkeypatching and abusing syntax, this would work:

class String
def | x
if empty? then x else self end
end
end

Then you can say word.infinitive | word, which actually scans fairly naturally, if you ask me.

However, I think a better idea would be to modify the infinitive method, or add a version of it that returns the word unchanged.

Edit: Here's a possibly more elegant solution:

[word.infinitive, word].find {|x| not x.empty?}

Convert an empty array to nil inplace

I wasn't able to find the answer using a search engine, but StackOverflow gave me the answer with a similar question, but then about strings:

Converting an empty string to nil in place?

The solution is to use presence

Only available within Rails.

Rails ||= for empty strings

you can try like this:

@my_var = ''
@my_var = @my_var.presence || 'This is a non-empty string'

Thanks :-)

Converting empty string to nil via split()

If you're doing this in rails, you can use the Object#presence method:

foo, bar, baz, etc = str.split(',').map(&:presence)

Ruby/Rails using || to determine value, using an empty string instead of a nil value

Rails adds presence method to all object that does exactly what you want

input = ''
value = input.presence || "default"
=> "default"

input = 'value'
value = input.presence || "default"
=> "value"

input = nil
value = input.presence || "default"
=> "default"


Related Topics



Leave a reply



Submit