条件如何处理?
如果结果为零,那么我得到 NoMethodError - undefined method 'length' for nil:NilClass:
有什么方法我不必使用两个条件吗? 我想如果结果为空,则 ruby 不会评估条件的第二部分,因为条件永远不会为真。
if (not results.empty? && results[-1].length == 2)
(4-results[-1].length).times {|i| results[-1] << ""}
end
If the results is nil then I get NoMethodError - undefined method 'length' for nil:NilClass:
Is there any way I don't have to use two conditions? I thought that ruby won't evaluate the second part of the condition in case results is empty because the condition can be never true.
if (not results.empty? && results[-1].length == 2)
(4-results[-1].length).times {|i| results[-1] << ""}
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会考虑将其更改为 IMO 更好地“读取”的内容:
为了避免两个明确的条件,请安装 andand gem:
I'd consider changing it to something that IMO "reads" better:
To avoid two explicit conditions, install the andand gem:
在 ruby 中,
not
运算符的优先级低于 < code>&& 因此您的代码被解释为您可能想要使用 !相反,它的作用与
not
相同,但优先级更高。In ruby the
not
operator has lower precedence than&&
so your code is being interpreted asYou probably want to use the ! operator instead which does the same as
not
but has higher precedence.