Created
April 22, 2022 21:43
-
-
Save fallwith/626ab750d76774bdfb4e4105393bedc3 to your computer and use it in GitHub Desktop.
Annotated submission for the 'phone-number' Exercism exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Any variable starting with a capital letter (including a class name!) is a | |
# constant in Ruby. For static values like this one, Rubyists typically use all | |
# caps for the variable name. | |
# | |
# %w = word array, use spaces without commas to delimit values | |
# | |
# #freeze, available on any instance of an object, prevents a value from being | |
# modified after it has been frozen. There is no #thaw or #unfreeze, but the | |
# value itself can be overwritten later if need be. | |
INVALID_CODES = %w[0 1].freeze | |
class PhoneNumber | |
# self. methods are "class" methods or "static" methods as opposed to | |
# instance methods | |
def self.clean(input) | |
# remove any non-numeric character. use gsub (instead of gsub!) to preserve | |
# the original input which may be needed for subsequent use by the caller | |
numbers = input.gsub(/[^\d]/, '') | |
# insist that there be exactly 10 or 11 digits (not more, not fewer) | |
return unless [10, 11].include?(numbers.size) # use #size or #length | |
if numbers.size == 11 | |
# 11 digit numbers should feature a 1 before the area code. If a 1 is | |
# found, good, remove it to shrink the string down to 10 digits in size | |
if numbers.start_with?('1') | |
# Ruby strings are zero indexed with the first character found at | |
# position 0. `1..10` is a range that means "the second through the | |
# eleventh character". This could also be written as `1..` which would | |
# mean "the second through the last character". | |
numbers = numbers[1..10] | |
# If something other than a 1 is found, short circuit | |
else | |
return | |
end | |
end | |
# For a given 10 digit phone number, neither the area code at the first | |
# positon or the exchange code at the fourth position can be a '0' or a '1' | |
return if INVALID_CODES.include?(numbers[0]) || | |
INVALID_CODES.include?(numbers[3]) | |
# Ruby methods will return the result of the final operation performed by | |
# the method. No need for an explicit 'return' statement unless we wish to | |
# return early from the method. | |
numbers | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment