在Ruby中将空字符串转换为nil [英] Converting an empty string into nil in Ruby
问题描述
我有一个名为 word
的字符串和一个名为 infinitive
的函数,使得 word.infinitive
有时会返回另一个字符串,否则会返回一个空字符串
我正在尝试为
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
如果不定式返回nil而不是",我可以做类似的事情
Had infinitive returned nil instead of "", I could have done something like
(word.infinitive or word)
但是由于没有,我无法利用短路OR
理想情况下,我想要
1)一个我可以轻松嵌入其他代码的表达式
2)不定式函数仅被调用一次
3)不要在我的代码中添加任何自定义的gem或插件
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:
class String
def | x
if empty? then x else self end
end
end
然后您可以说 word.infinitive |单词
,如果您问我,它实际上会自然扫描.
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.
这是一个可能更优雅的解决方案:
Here's a possibly more elegant solution:
[word.infinitive, word].find {|x| not x.empty?}
这篇关于在Ruby中将空字符串转换为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!