I have a string called word
and a function called infinitive
such thatword.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
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.
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 ).
In Ruby, an empty string "" is truthy with respect to conditionals.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With