使用 || 的 Ruby/Rails确定值,使用空字符串而不是 nil 值 [英] Ruby/Rails using || to determine value, using an empty string instead of a nil value
本文介绍了使用 || 的 Ruby/Rails确定值,使用空字符串而不是 nil 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常这样做
value = input || "default"
所以如果 input = nil
so if input = nil
value = "default"
但是我怎么能这样做而不是 nil
它还将空字符串 ''
计算为 nil
But how can I do this so instead of nil
It also counts an empty string ''
as nil
如果我愿意
input = ''
value = input || "default"
=> "default"
没有if
,有没有一种简单优雅的方法来做到这一点?
Is there a simple elegant way to do this without if
?
推荐答案
Rails 添加了 presence 方法用于所有完全符合您要求的对象
Rails adds presence method to all object that does exactly what you want
input = ''
value = input.presence || "default"
=> "default"
input = 'value'
value = input.presence || "default"
=> "value"
input = nil
value = input.presence || "default"
=> "default"
这篇关于使用 || 的 Ruby/Rails确定值,使用空字符串而不是 nil 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文