Ruby Printing variable within a String, Phone Validation -
i'm trying variables output in string. when print below isn't formatting correctly new line each title , variable.
print "user: #{names}\nphone: #{valid_phone?(number)}\n email: #{email}"
i'm getting output:
user: ["john", "doe\n"] phone: 555-555 email: johndoe@info.com
output should appear as:
user: john doe phone: (555)555-5555 email: johndoe@info.com
i'm not getting phone number output in format of (555)555-5555. here full code. thanks!!
name_pattern = /([\w\-\']{2,})([\s]+)([\w\-\']{2,})/ email_pattern = /\a([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i phone_pattern = /^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/ def valid_name?(name) !!name.match(name_pattern) end puts "enter first , last name (john doe): " while (name=gets) names = name.split(" ", 2) if valid_name?(name) puts "great, looks work." break else puts "invalid entry, please enter first , last name. exit press ctrl+c." end end def valid_email?(email) !!email.match(email_pattern) end puts "enter email address (joe@info.com): " while (email = gets) if valid_email?(email) puts "great, looks work." break else puts "invalid email address entered. please try again. exit press ctrl+c." end end puts "enter phone number including area code (numbers only): " def valid_phone?(number) !!number.match(phone_pattern) number = number.to_s area_code = number.length == 10 ? "(#{number[0..2]}) " : '' office_code = number[-7..-5] specific_line = number[-4..-1] "#{area_code}#{office_code}-#{specific_line}" end while (number=gets) if valid_phone?(number) puts "great, looks work." break else puts "invalid phone number entered. please try again. exit press ctrl+c." end end print "user: #{names}\nphone: #{valid_phone?(number)}\n email: #{email}"
to expected output replace last line (print
) following
puts "user: #{names.join(' ')}" puts "phone: #{valid_phone?(number)}" puts "email: #{email}"
also change line number = number.to_s
number = number.chomp