“OrElse”处的 Ruby 等效运算符和“还有” Vb.net 的
Ruby 中是否有类似于 VB.NET 中的“OrElse”和“AndAlso”的运算符?
例如,在 Ruby 中,当 active_record 为 nil 时,会引发 NoMethodError 异常:
if active_record.nil? || active_record.errors.count == 0
...
end
在 VB.net 中,我可以这样做:
If active_record Is Nothing OrElse active_record.errors.count = 0
...
End
这不会生成异常,因为它只检查第一个表达式
There are operators in Ruby similar to "OrElse"and "AndAlso" in VB.NET?
For example in Ruby NoMethodError exception is raised when active_record is nil:
if active_record.nil? || active_record.errors.count == 0
...
end
In VB.net i can do:
If active_record Is Nothing OrElse active_record.errors.count = 0
...
End
That does not generate an exception because it is only checked the first expression
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,不会引发异常(因为只会评估 || 中的第一项)。但是,您可能有兴趣阅读 ActiveSupport 中的 Object#try ,这在处理可能为零的对象时很有帮助。
In this case there will be no exception raised (because only the first term in || will be evaluated). However you might be interested in reading about Object#try from ActiveSupport, which can be helpful when dealing with objects that can be nil.
在 Ruby 中,零和未定义的东西之间有很大的区别。考虑以下来自 IRB 的内容:
因此,一个 nil 的对象是 NilClass 的一个实例,因此响应消息
nil?
将返回 true,但不声明变量(如在您的代码中)Ruby不知道你在叫什么。这里有几个选项:
Ruby 的
||
运算符是严格运算符,而or
关键字不太严格,所以我不知道 vb 操作与这些操作相比在哪里两个或流选项。你可以使用一个名为 'andand' 的简洁小 gem,
但是,通常当你在 Rails 中处理这种情况时,您将使用另一种方法来确定上述情况,请考虑:
如果您打算根据某些内容是否可能未定义来分配某些内容,则您需要使用记忆化:
如果未定义,它将声明该对象或使用现有对象
in ruby, there is a big difference between something that is nil and something that is undefined. Considering the following, from IRB:
So, an object that is nil is an instance of NilClass and therefore responds to the message
nil?
will return true, but without declaring the variable (as in your code) Ruby doesn't know what you are calling.A couple of options here:
Ruby's
||
operator is a strict operator, whereas theor
keyword is less strict, so I don't know where the vb operation compares to these two or flow options.you could use a neat little gem callled 'andand'
but, generally when you are dealing with this situation in rails, you would use another means to determine the situation above, consider:
and if you mean to assign something based on if it possibly undefined, you would want to use memoization:
which will declare the object if undefined or use the existing object
Ruby
||
是 短路评估 运算符,所以它应该仅评估第一个条件,因此您的if
不应引发任何异常。我假设
active_record.nil?
返回布尔值true
。Ruby
||
is short circuit evaluation operator, so it should evaluate only first condition, therefore yourif
should not raise any exception.I assume
active_record.nil?
returns booleantrue
.