Created
January 16, 2021 04:42
-
-
Save VishalTaj/770b7aa802451dc0706fbaa8918d1c32 to your computer and use it in GitHub Desktop.
phone number formatter
This file contains 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
class Phone | |
attr_accessor :num, :code | |
def initialize(num, code) | |
self.code = code | |
self.num = num | |
end | |
def to_num | |
rec = num.gsub(/[^\d]/, '') | |
if rec[0..2] == code | |
rec | |
elsif rec[0] == "0" | |
"#{code}#{rec[1..-1]}" | |
else | |
"#{code}#{rec}" | |
end | |
end | |
def to_hyphen(delimiter = '-') | |
<<<-DOC | |
R = / | |
\d{2,3} # match 2 or 3 digits (greedily) | |
(?= # begin positive lookahead | |
\d{2,3} # match 2 or 3 digits | |
| # or | |
\z # match the end of the string | |
) # end positive lookahead | |
/x # free-spacing regex definition mode | |
DOC | |
R = /\d{2,3}(?=\d{2,3}|\z)/ | |
s = num.gsub(/\D/,'') | |
return s if s.size < 4 | |
s.scan(R).join(delimeter) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment