Reputation: 25
I am trying to find out if a string includes more than two occurrences of a certain symbol. For example,
is_valid_email("joey@[email protected]")
should return false
if there are more than two "@"
or "."
. Can I use something like this?
if string.include?("@") > 2
return false
else
return true
end
Upvotes: 0
Views: 91
Reputation: 95315
You can use String#count
. Also, there's not much point in an if
statement that just returns true
or false
; the boolean condition itself is already true
or false
, so you can simply return it directly. In this case, since the if
part returns false
and the else
returns true
, you can negate the condition:
return !(string.count('@') >= 2)
Or use the opposite condition:
return string.count('@') < 2
But if you're validating that a string looks like an email address, it seems like you would want to make sure it contains exactly one "@":
return string.count('@') == 1
You can leave the return
keyword off as long as there's no additional code after this check in the method body; a method automatically returns the value of its last expression.
Upvotes: 5