Home > Net >  How do I check if a user input contains a period (.) in Ruby?
How do I check if a user input contains a period (.) in Ruby?

Time:10-12

I am trying to check that 3 condiditons are met when asking a user for an email. The user must input something, they must include the @ symbol, and include a domain (.com, .edu, .net, etc). For the domian I am mainly checking for a period. how do i make sure the user input meets these 3 conditions?

Here is the code I use:

    def email()
        print "What is the students email? "
        email = gets.chomp

        if email.empty? && email.include?("@") && email.include?(".")
            puts "working"
        else
            puts "Please enter a valid email. "
            email()
        end 
    end

    email()

Here is an example of me running the method in terminal:

Terminal output

I am using Ruby and VScode.

CodePudding user response:

You can use simple regexp like this

email.match?(/\A. @. \.. \z/)
/
  \A  # string begin
  .   # minimum 1 character
  @   # @
  .   # minimum 1 character
  \.  # dot
  .   # minimum 1 character
  \z  # string end
/x

CodePudding user response:

As noted in comments your condition is impossible. If a string is empty, it cannot contain anything.

A very minor change is needed to check that the string is not empty.

if !email.empty? && email.include?("@") && email.include?(".")
  puts "working"
else
  puts "Please enter a valid email. "
  email()
end 
  •  Tags:  
  • ruby
  • Related