13

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?

Dean
  • 8,668
  • 17
  • 57
  • 86
  • 1
    Looks right, although, you don't need the outer parenthesis. Can you post some more information about your problem? – Jim Deville Jan 19 '13 at 20:01

4 Answers4

32

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

Community
  • 1
  • 1
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
6

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
steenslag
  • 79,051
  • 16
  • 138
  • 171
5

I forgot end_with? takes multiple arguments:

unless email_address.end_with?("@domain1.com", "@domain2.com")
 #do something
end
steenslag
  • 79,051
  • 16
  • 138
  • 171
3

How about:

(!email_address[/@domain[12]\.com\z/])
the Tin Man
  • 158,662
  • 42
  • 215
  • 303