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 == trueinstead ofthis = true.andandorinstead of&&and||– they are not equivalent. Read up on operator precedence in ruby, it’s subtly different than in other languages such as PHP. You’re probably better off sticking with&&and||for most logical statements and reserving the use oforandandto control flow, such asredirect and return.So your concrete example should probably look like this:
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.