Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an empty string into nil in Ruby

Tags:

I have a string called word and a function called infinitive such that
word.infinitive would return another string on some occasions and an empty string otherwise
I am trying to find an elegant ruby one line expression for the code-snippet below

if word.infinitive == ""       return word else return word.infinitive 

Had infinitive returned nil instead of "", I could have done something like

(word.infinitive or word) 

But since it does not, I can't take advantage of the short-circuit OR
Ideally I would want
1) a single expression that I could easily embed in other code
2) the function infinitive being called only once
3) to not add any custom gems or plugins into my code

like image 516
Aditya Mukherji Avatar asked Mar 15 '09 05:03

Aditya Mukherji


People also ask

Is empty string nil Ruby?

nil? will only return true if the object itself is nil. That means that an empty string is NOT nil and an empty array is NOT nil.

How do I convert a string to an empty number?

Multiplying a string by 1 ( [string] * 1 ) works just like the unary plus operator above, it converts the string to an integer or floating point number, or returns NaN (Not a Number) if the input value doesn't represent a number. Like the Number() function, it returns zero ( 0 ) for an empty string ( '' * 1 ).

Is empty string true in Ruby?

In Ruby, an empty string "" is truthy with respect to conditionals.


1 Answers

The ActiveSupport presence method converts an empty (or blank?) string to nil. It's designed for your exact use case:

word.infinitive.presence || word 

Note that you can easily use ActiveSupport outside of rails:

require 'active_support/core_ext/object/blank' 
like image 140
David Phillips Avatar answered Oct 10 '22 03:10

David Phillips