[英]Ruby logic and/or chains
I am trying to write some validation logic inside of a model for one of my applications. 我正在尝试为我的一个应用程序在模型内部编写一些验证逻辑。 The logic I would like to build in looks like this. 我要构建的逻辑如下所示。
def validation
if this == true or (!that.nil? and those < 1000)
do something
else
do nothing
end
Is it possible to do this within a ruby method? 是否可以在红宝石方法中执行此操作?
Sure you can. 你当然可以。 However, two things to be aware of: 但是,需要注意两件事:
this == true
instead of this = true
. 我怀疑您的意思是this == true
而不是this = true
。 and
and or
instead of &&
and ||
在使用and
和or
代替&&
和||
时要非常小心 - they are not equivalent. -它们不相等。 Read up on operator precedence in ruby , it's subtly different than in other languages such as PHP. 阅读ruby中的运算符优先级 ,它与其他语言(例如PHP)有细微的区别。 You're probably better off sticking with &&
and ||
您最好坚持使用&&
和||
for most logical statements and reserving the use of or
and and
to control flow, such as redirect and return
. 对于大多数逻辑语句,并保留使用or
和and
控制流,例如redirect and return
。 So your concrete example should probably look like this: 因此,您的具体示例应如下所示:
if this == true || (!that.nil? && those < 1000)
do something
else
do nothing
end
In this particular case, the parentheses are redundant, since &&
precedes ||
在此特定情况下,括号是多余的,因为&&
在||
之前 , but they don't hurt, and for anything more complicated, it's good practice to use them to avoid ambiguity and subtle bugs due to a misunderstanding of operator precedence. ,但它们不会造成伤害,对于更复杂的事物,最好使用它们来避免由于对运算符优先级的误解而造成的歧义和细微的错误。
Sure, i would only recommend you to create smaller methods like a method compare each of the attributes and on that method call them. 当然,我只建议您创建较小的方法,例如比较每个属性的方法,并在该方法上调用它们。
def validation
if this? or others?
#do something
else
#do nothing
end
end
private
def others?
that? and those?
end
def this?
this == true
end
def that?
that != nil
end
def those?
those < 1000
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.