如何用连字符在Ruby中格式化电话字符串?

时间:2019-01-31 01:55:28

标签: ruby string-formatting

我有一个无法解决的问题。 我需要编写一种phone_format方法,该方法可以接受任何电话字符串,并以连字符(3位数字)的形式将其输出。

phone_format("555 123 1234") => "555-123-12-34"

phone_format("(+1) 888 33x19") => "188-833-19"

但是,如果它以999-9之类的一位数字结尾,请将其更改为99-99。理想情况下,这将是一个班轮

2 个答案:

答案 0 :(得分:1)

并不是真正的一站式服务:您需要处理特殊情况。

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

答案 1 :(得分:1)

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

按惯例写

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"