Looking at your current code first, I noticed the following:
You should use email.split('@').last
instead of an opaque numeric index (plus, you'll always get a string this way, whereas using [1]
will return nil
if the address doesn't contain an "@" to begin with)
You should probably downcase the address you're trying to match (provided the university domains are similarly downcased, of course)
You never need to loop, check a condition, and set a variable + break
if that condition is true. The reason you don't need to that is because you have Enumerable#detect
to do it for you.
This looks like a Rails project, so it'd probably be faster to either let the database check for you, or only load the column you need, instead of loading every single University
record.
For instance, to let the DB check it, you can do this
match = University.where("? LIKE CONCAT('%', domain)", self.email).any?
errors.add(:email, "Sorry, no match found") unless match
Since you're not actually loading any records doing this, I'd imagine it's pretty fast (and case-insensitive, so no need for downcasing)
As for matching things in Ruby, Nat's approach is the most straightforward one, I'd say.
I'd still do it a bit differently, though:
address = self.email.downcase
# only load the domain column values, since those are all we need here
match = University.pluck(:domain).detect { |domain| address.end_with?(domain) }
errors.add(:email, "Sorry, no match found") unless match
Of course, you should still check that the address is a valid email address in its entirety.