Ruby - 变量不为 NULL 并且包含一个字符串
我正在将数据存储在数据库表中。列中可以是值 NULL 和字符串。我找不到条件,when is a string ->打印这个字符串,当 NULL 时,做其他事情...
我正在尝试这样的事情:
if @optional.logo.size > 3 && [email protected]?
...In table is a STRING...
else
...In table is NULL...
end
但这是错误的...任何人都可以帮助我,请如何修复它? 感谢您
I am storing in DB table data. In a column could be the value NULL and a string. And I can't to find a condition, when is a string -> print this string, when is NULL, do something else...
I am trying something like this:
if @optional.logo.size > 3 && [email protected]?
...In table is a STRING...
else
...In table is NULL...
end
but this is wrong... Can anyone help me, please, how to fix it?
Thanks you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须首先测试 nil,因为 nil 对象不会具有
size
属性。You'll have to test for nil first because a nil object will not have the
size
property.切换过来,首先进行
nil
检查:&&
运算符就是所谓的“短路”。这意味着如果第一个参数的计算结果为 false,则永远不会计算第二个参数,因为这并不重要。换句话说,如果第一个参数为 false,则无论参数部分如何,整个表达式都将为 false。||
运算符的工作原理类似,但如果第一个参数为 true,则不会计算第二个参数,因为无论第二个参数的值如何,整个表达式都为 true。通过首先检查
nil
,您可以避免nil
没有size
方法的问题,因为表达式的该部分永远不会被计算。Switch it around and do the
nil
check first:The
&&
operator is what is called "short circuiting". That means that if the first argument evaluates to false the second is never evaluated, since it wouldn't matter. In other words, if the first argument is false the whole expression will be false regardless of the argument part. The||
operator works similarly, but does not evaluate the second argument if the first is true, since that makes the whole expression true regardless of the second argument's value.By checking for
nil
first you avoid the issue thatnil
will not have asize
method, since that part of the expression will never be evaluated.