Reputation: 126
I have a problem I can't solve.
I need to write phone_format
method that would accept any phone string and output it in groups of 3 digits with hyphens
phone_format("555 123 1234") => "555-123-12-34"
phone_format("(+1) 888 33x19") => "188-833-19"
But if it ends with single digit like 999-9
, change it to 99-99
. Ideally it would be a one liner
Upvotes: 0
Views: 1266
Reputation: 110685
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
Conventionally written
R = /\d{2,3}(?=\d{2,3}|\z)/
def doit(str)
s = str.gsub(/\D/,'')
return s if s.size < 4
s.scan(R).join('-')
end
doit "555 123 123"
#=> "555-123-123"
doit "555 123 1234"
#=> "555-123-12-34"
doit "555 123 12345"
#=> "555-123-123-45"
doit "(+1) 888 33x19"
#=> "188-833-19"
doit "123"
#=> "123"
doit "1234"
#=> "12-34"
Upvotes: 3
Reputation: 198334
Not really a one-liner: you need to handle the special cases.
def cut_by(str, cut)
str.each_char.each_slice(cut).map(&:join).join('-')
end
def phone_format(str)
str = str.gsub(/\D/, '') # cleanup
if str.size == 4 # special case 1
cut_by(str, 2)
elsif str.size % 3 == 1 # special case 2
cut_by(str[0..-5], 3) + "-" + cut_by(str[-4..], 2)
else # normal case
cut_by(str, 3)
end
end
Upvotes: 1