I am new to ruby. I am trying to parse phone numbers from a CSV file and I did that using the following code. It is working properly.
require 'csv'
csv_text = File.read('file.csv')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
puts "Home Phone: #{row['HomePhone']}"
end
What I want is to clean up HomePhone in the following ways.
- If phone number has 10 digits, it is good, print it as such.
- If phone number has less than 10 digits, print invalid number as “0000000000”
- If phone number has 11 digits and first digit is 1, print last 10 digits (remove first 1), else “0000000000”
I don’t know how to do this.
You can get the length of a string with the aptly-named
lengthmethod:You can check if a string starts with another string using
start_with?:You can slice a string individual characters using array index notation (square brackets) and a range. A negative index counts from the end of the string. So to return all but the first character:
So to do what you are asking you can combine these
Note that this approach assumes that your phone numbers are already strings of digits and you just need to check their length. If you wanted to be more thorough and check for invalid phone numbers containing non-digits, like
123z567890, you might consider a regex approach:The components that this regex matches are:
^– the start of the string1?– an optional1(?<number>\d{10})– 10 digits (ie\d{10}) saved in a group callednumber$– the end of the stringRuby uses the forward slashes to delimit the regex, and the
matchmethod returns an object that we can use to extract the saved 10-digit number.