Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 Conditions in if statement

Tags:

ruby

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?

like image 289
Dean Avatar asked Jan 19 '13 19:01

Dean


People also ask

Can IF statement have 2 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.

How do you write if in two conditions?

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.

Can if statements have 3 conditions?

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.


2 Answers

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

From the comments:

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 !.

like image 176
Michael Berkowski Avatar answered Oct 16 '22 17:10

Michael Berkowski


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
like image 24
steenslag Avatar answered Oct 16 '22 18:10

steenslag