I am trying to detect if the email address is not one of two domains but I am having some trouble with the ruby syntax. I currently have this:
if ( !email_address.end_with?("@domain1.com") or !email_address.end_with?("@domain2.com"))
#Do Something
end
Is this the right syntax for the conditions?
Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.
Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.
If you have to write an IF statement with 3 outcomes, then you only need to use one nested IF function. The first IF statement will handle the first outcome, while the second one will return the second and the third possible outcomes. Note: If you have Office 365 installed, then you can also use the new IFS function.
Rather than an or
here, you want a logical &&
(and) because you are trying to find strings which match neither.
if ( !email_address.end_with?("@domain1.com") && !email_address.end_with?("@domain2.com"))
#Do Something
end
By using or
, if either condition is true, the whole condition will still be false.
Note that I am using &&
instead of and
, since it has a higher precedence. Details are well outlined here
You can build an equivalent condition using unless
with the logical or ||
unless email_address.end_with?("@domain1.com") || email_address.end_with?("@domain2.com")
This may be a bit easier to read since both sides of the ||
don't have to be negated with !
.
If more domains are added, then the repetitive email_address.end_with?
is getting boring real fast. Alternative:
if ["@domain1.com", "@domain2.com"].none?{|domain| email_address.end_with?(domain)}
#do something
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With