Instructions
Create a function valid_email? that checks if a string looks like
a valid email address using a regular expression.
A simple email pattern should match:
- One or more word characters before @
- The @ symbol
- One or more word characters for domain
- A dot
- 2-4 letters for TLD
Use match? to check if a string matches a pattern:
ruby
"test".match?(/pattern/) # Returns true or false
Hints:
- Use \w+ for word characters (letters, digits, underscore)
- Escape the dot with \.
- Pattern: /\w+@\w+\.\w{2,4}/
Your Code
def valid_email?(email)
email.match?(/\A\w+@\w+\.\w{2,4}\z/)
end
RSpec.describe "valid_email?" do
it "returns true for valid email" do
expect(valid_email?("user@example.com")).to be true
end
it "returns true for email with numbers" do
expect(valid_email?("user123@test.org")).to be true
end
it "returns false without @" do
expect(valid_email?("userexample.com")).to be false
end
it "returns false without domain" do
expect(valid_email?("user@.com")).to be false
end
it "returns false without TLD" do
expect(valid_email?("user@example")).to be false
end
end
Results
Click "Run Tests" to see results