Quick and dirty nil and empty string handling in Ruby
I've run across issues with empty strings and nil values quite a bit lately - seems like mostly in relation to an API interfacing with iOS. Here are two quick tips:To ensure that no
nil
values are given, I can call .to_s
on any string values or values that should be strings. If one of them is nil
, it will convert it to an empty string. If it's already a string, it will just leave it alone. How about going the other way?
.presence
is the key. Call .presence
on an empty string and it will give back nil
. If the string isn't empty it will return the original string. TL;DR:
"".presence
# => nil
"hey".presence
# => "hey"
nil.to_s
# => ""
"hey".to_s
# => "hey"