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
If you’re not ashamed of monkeypatching and abusing syntax, this would work:
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: