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
Ruby Classes: Initialize Self VS. @Variable
How to Use Nokogiri to Parse an Xml File
How to Use Ruby Minitest::Spec with Rails for API Integration Tests
Post JSON Data to Simple Rails Application with Curl
What's the Most Efficient Way to Deep Copy an Object in Ruby
Should I Use Class Method or Instance Method, and Why
Rails - Testing JSON API with Functional Tests
Check Ruby Http Response for Success
How to Attach a Message to Rspec Check
How to Make Sign Up Page Be Root Page in Devise
How to Use Active Record Without Rails
Error Installing Any Ruby Version with Rvm on Osx
Suitability of Rails, Padrino, and Sinatra for Building a Prepaid Mobile Service
Ruby Remove Empty Lines from String
How to Solve the Update Bundler Warning in Rails When Deploying to Heroku